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。

feat(session): 支持通过运行时工具切换 harness (#4345)

Dash34c2bffdf430
diff --git a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
index d61a2bfd4c..79909f0a4c 100644
--- a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
@@ -45,6 +45,18 @@ const useOrcaWorkerSelectionSourcePath = resolve(__dirname, '..', '..', 'rendere
const useOrcaWorkerSelectionSource = readFileSync(useOrcaWorkerSelectionSourcePath, 'utf8').replace(/\r\n?/g, '\n');
describe('sendToSession ordering', () => {
+ it('routes pending harness selections through the canonical queued send before using a live handle', () => {
+ const block = extractSendToSessionSource();
+ const routing = block.indexOf('|| agentSwitchPending.get(targetSessionId)');
+ expect(routing).toBeGreaterThan(0);
+ const enqueue = block.indexOf('await enqueueSendToSessionMessage({', routing);
+ const queuedReply = block.indexOf("wakeKind: 'queued'", enqueue);
+ const liveRead = block.indexOf('let live = maker.getSession(targetSessionId)');
+ expect(enqueue).toBeGreaterThan(routing);
+ expect(queuedReply).toBeGreaterThan(enqueue);
+ expect(queuedReply).toBeLessThan(liveRead);
+ });
+
it('routes even idle private Bot deliveries through the durable input coordinator', () => {
const block = extractSendToSessionSource();
const routing = block.indexOf("explicitClientId?.startsWith('bot-dm:') || explicitClientId?.startsWith('bot-authorization-resume:') || inputCoordinator.shouldQueueNewTurn(targetSessionId)");
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 9de6a450d0..6c86d1ce66 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts
@@ -839,6 +839,33 @@ describe('Phase 2:切回停泊引擎(resume + 增量交接)', () => {
});
}
+ it.each([false, true])('Agent recovery retains its source and blocks sending (missing boundary=%s)', async (missingBoundary) => {
+ const pending = createPendingAgentSwitchRegistry();
+ const { deps } = makeResumeDeps({
+ pendingSwitches: pending,
+ bootstrapSwitchedSession: vi.fn(async () => { throw new Error('resume unavailable'); }),
+ applyResumeFallbackAtomically: vi.fn(async () => { throw new Error('transaction unavailable'); }),
+ ...(missingBoundary ? { insertBoundaryMessage: vi.fn(async () => { throw new Error('boundary unavailable'); }) } : {}),
+ });
+ await performSessionAgentSwitch(deps, { ...validParams, runtimeSource: 'agent' });
+ await expect(applyPendingAgentSwitchIfIdle(deps, 's1')).rejects.toThrow('recovery is pending');
+ expect(pending.get('s1')).toMatchObject({ runtimeSource: 'agent', resumeFallbackRecovery: { boundaryClientId: missingBoundary ? null : 'boundary-client-1' } });
+ await expect(applyPendingAgentSwitchIfIdle(deps, 's1')).rejects.toThrow(missingBoundary ? 'boundary unavailable' : 'transaction unavailable');
+ expect(pending.get('s1')?.runtimeSource).toBe('agent');
+ });
+
+ it('consumes an Agent harness selection through the existing history handoff transaction', async () => {
+ const pending = createPendingAgentSwitchRegistry();
+ const { deps, calls } = makeResumeDeps({ pendingSwitches: pending });
+ await performSessionAgentSwitch(deps, { ...validParams, runtimeSource: 'agent' });
+ expect(calls).toEqual([]);
+ await applyPendingAgentSwitchIfIdle(deps, 's1');
+ expect(calls).toContain('db');
+ expect(calls).toContain('boundary');
+ expect(calls).toContain('bootstrap');
+ expect(pending.get('s1')).toBeUndefined();
+ });
+
it('有停泊绑定:DB 落停泊 id、交接为增量模式、边界行标 resumed', async () => {
const { deps } = makeResumeDeps();
const result = await performSessionAgentSwitch(deps, validParams);
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionRuntimeHarnessSelection.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionRuntimeHarnessSelection.test.ts
new file mode 100644
index 0000000000..e695f1dfee
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionRuntimeHarnessSelection.test.ts
@@ -0,0 +1,227 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ applyPendingAgentSwitchIfIdle,
+ createPendingAgentSwitchRegistry,
+ performSessionAgentSwitch,
+ type MakerSessionAgentSwitchHandlerDeps,
+} from '../sessionAgentSwitchHandler';
+import {
+ pendingHarnessRuntimeMutation,
+ setSessionRuntimeHarness,
+ type HarnessRuntimeSelectionDeps,
+} from '../sessionRuntimeHarnessSelection';
+import type { SessionRuntimeProfile } from '../sessionRuntimeControl';
+
+function setup(running = false) {
+ let generation = 4;
+ let owner = 'owner-1';
+ const pending = createPendingAgentSwitchRegistry();
+ const effective: SessionRuntimeProfile = {
+ agentKind: 'claude-code',
+ model: 'claude-fable-5',
+ providerId: 'old-provider',
+ effort: 'high',
+ fastMode: false,
+ };
+ const close = vi.fn();
+ const persist = vi.fn();
+ const switchDeps = {
+ getSessionRow: vi.fn(async () => ({
+ id: 's1',
+ agentKind: 'cc',
+ model: effective.model,
+ providerId: 'old-provider',
+ status: 'active',
+ remoteHostId: null,
+ orcaRole: null,
+ sdkSessionId: 'native-1',
+ })),
+ getLiveSession: () => ({ isTurnRunning: () => running }),
+ pendingSwitches: pending,
+ onPendingSwitchChanged: () => {
+ generation++;
+ },
+ closeSession: close,
+ applyAgentSwitchToDb: persist,
+ supersedePendingCredentialSwitch: vi.fn(),
+ log: { info: vi.fn(), warn: vi.fn() },
+ } as unknown as MakerSessionAgentSwitchHandlerDeps;
+ const deps: HarnessRuntimeSelectionDeps = {
+ withSessionLock: async (_id, run) => run(),
+ ownerEpoch: () => owner,
+ generation: () => generation,
+ pendingRevision: (id) => pending.revision!(id),
+ read: vi.fn(async () => effective),
+ resolve: vi.fn(async (profile) => ({ ...profile, providerId: profile.providerId ?? 'openai' })),
+ stage: (id, profile, assertCurrent) =>
+ performSessionAgentSwitch(switchDeps, {
+ sessionId: id,
+ targetAgentKind: profile.agentKind,
+ model: profile.model,
+ providerId: profile.providerId,
+ effort: profile.effort,
+ fastMode: profile.fastMode,
+ runtimeSource: 'agent',
+ assertSelectionCurrent: assertCurrent,
+ }),
+ pending: (id) => pending.get(id),
+ };
+ return {
+ deps,
+ pending,
+ switchDeps,
+ close,
+ persist,
+ effective,
+ bump: () => generation++,
+ logout: () => {
+ owner = 'owner-2';
+ },
+ };
+}
+
+const request = {
+ targetSessionId: 's1',
+ expectedGeneration: 4,
+ patch: { harness: 'codex' as const, model: 'gpt-6-astra' },
+};
+
+describe('runtime harness selection', () => {
+ it('blocks sending on the old harness when the accepted target becomes unavailable', async () => {
+ const h = setup();
+ await setSessionRuntimeHarness(h.deps, request);
+ const intent = h.pending.get('s1');
+ h.switchDeps.assertModelRouteUsable = async () => {
+ throw new Error('provider disabled');
+ };
+ await expect(applyPendingAgentSwitchIfIdle(h.switchDeps, 's1')).rejects.toThrow(
+ 'provider disabled',
+ );
+ expect(h.pending.get('s1')).toBe(intent);
+ expect(h.close).not.toHaveBeenCalled();
+ });
+
+ it.each([false, true])(
+ 'stages until send, without interrupting or persisting (running=%s)',
+ async (running) => {
+ const h = setup(running);
+ const result = await setSessionRuntimeHarness(h.deps, request);
+ expect(result).toMatchObject({
+ ok: true,
+ status: 'deferred',
+ effectiveBoundary: 'next_send',
+ generation: 5,
+ effectiveProfile: h.effective,
+ pendingMutation: {
+ generation: 5,
+ source: 'agent',
+ profile: { agentKind: 'codex', model: 'gpt-6-astra', providerId: 'openai' },
+ },
+ });
+ expect(h.close).not.toHaveBeenCalled();
+ expect(h.persist).not.toHaveBeenCalled();
+ expect(pendingHarnessRuntimeMutation(h.pending.get('s1'), 5)).toEqual(
+ result.ok && result.pendingMutation,
+ );
+ },
+ );
+
+ it.each(['stale', 'during-resolution', 'during-row-read', 'logout', 'intent-revision'])(
+ 'rejects concurrent mutation: %s',
+ async (when) => {
+ const h = setup();
+ if (when === 'stale') h.bump();
+ if (when === 'during-resolution')
+ h.deps.resolve = async (p) => {
+ h.bump();
+ return p;
+ };
+ if (when === 'logout')
+ h.deps.resolve = async (p) => {
+ h.logout();
+ return p;
+ };
+ if (when === 'intent-revision')
+ h.deps.resolve = async (p) => {
+ h.pending.clear('s1');
+ return p;
+ };
+ if (when === 'during-row-read') {
+ const read = h.switchDeps.getSessionRow;
+ h.switchDeps.getSessionRow = async (id) => {
+ const row = await read(id);
+ h.bump();
+ return row;
+ };
+ }
+ expect(await setSessionRuntimeHarness(h.deps, request)).toMatchObject({
+ ok: false,
+ errorCode: 'CONFLICT',
+ });
+ expect(h.pending.get('s1')).toBeUndefined();
+ expect(h.switchDeps.supersedePendingCredentialSwitch).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([
+ { remoteHostId: 'ssh-host' },
+ { orcaRole: 'lead' },
+ { source: 'review' },
+ { status: 'deleted' },
+ { status: 'archived' },
+ ])('preserves existing intent when target is ineligible: %j', async (overrides) => {
+ const h = setup();
+ const previous = { targetAgentKind: 'pi' as const, model: 'old-choice', providerId: null };
+ h.pending.set('s1', previous);
+ const read = h.switchDeps.getSessionRow;
+ h.switchDeps.getSessionRow = async (id) => ({ ...(await read(id))!, ...overrides });
+ expect(await setSessionRuntimeHarness(h.deps, request)).toMatchObject({ ok: false });
+ expect(h.pending.get('s1')).toBe(previous);
+ expect(h.close).not.toHaveBeenCalled();
+ });
+
+ it('preserves selections after target route validation fails', async () => {
+ const h = setup();
+ h.deps.resolve = async () => {
+ throw Object.assign(new Error('unavailable target'), { code: 'INVALID_PARAMS' });
+ };
+ expect(await setSessionRuntimeHarness(h.deps, request)).toMatchObject({
+ ok: false,
+ errorCode: 'ROUTE_UNAVAILABLE',
+ });
+ expect(h.pending.get('s1')).toBeUndefined();
+ });
+
+ it('passes the CAS guard through same-harness model validation', async () => {
+ const h = setup();
+ h.switchDeps.selectSameAgentModel = async (_id, intent, applyNow, assertCurrent) => {
+ expect(intent.runtimeSource).toBe('agent');
+ expect(applyNow).toBe(false);
+ h.bump();
+ assertCurrent?.();
+ throw new Error('stale choice must not be staged');
+ };
+ expect(
+ await setSessionRuntimeHarness(h.deps, {
+ ...request,
+ patch: { harness: 'claude-code', model: 'claude-fable-5' },
+ }),
+ ).toMatchObject({ ok: false, errorCode: 'CONFLICT' });
+ });
+
+ it('requires model and generation and does not expose picker intents as Agent overrides', async () => {
+ const h = setup();
+ expect(
+ await setSessionRuntimeHarness(h.deps, { ...request, patch: { harness: 'codex' } }),
+ ).toMatchObject({ ok: false, errorCode: 'INVALID_ARGS' });
+ expect(
+ await setSessionRuntimeHarness(h.deps, { ...request, expectedGeneration: undefined }),
+ ).toMatchObject({ ok: false, errorCode: 'CONFLICT' });
+ expect(
+ pendingHarnessRuntimeMutation(
+ { targetAgentKind: 'codex', model: 'gpt-6-astra', providerId: null },
+ 4,
+ ),
+ ).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index d8e8eaf4c5..e535952c27 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -755,6 +755,7 @@ import {
registerMakerSessionAgentSwitchHandler,
type MakerSessionAgentSwitchHandlerDeps,
} from './sessionAgentSwitchHandler.js';
+import { pendingHarnessRuntimeMutation, setSessionRuntimeHarness } from './sessionRuntimeHarnessSelection.js';
import {
extractAgentIslandPromptText,
prependNoteToWireUserMessage,
@@ -1797,6 +1798,7 @@ interface OrcaCollabService {
targetSessionId: string;
expectedGeneration?: number;
patch: {
+ harness?: AgentKind;
model?: string;
providerId?: string | null;
effort?: import('@cindy/maker-core').Effort;
@@ -1806,6 +1808,7 @@ interface OrcaCollabService {
| {
ok: true;
status: 'applied' | 'deferred';
+ effectiveBoundary?: 'next_send';
generation: number;
effectiveProfile: SessionRuntimeProfile;
pendingMutation: ReturnType<typeof getPendingSessionRuntimeMutation>;
@@ -8168,11 +8171,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
},
withCloseSuppressed: withRehydrateCloseSuppressed,
pendingSwitches: agentSwitchPending,
- selectSameAgentModel: async (sessionId, intent, applyNow) => {
+ selectSameAgentModel: async (sessionId, intent, applyNow, assertSelectionCurrent) => {
const result = await applySessionRuntimeSelection(sessionId, intent.model, intent.providerId, {
effort: (intent.effort ?? null) as SessionRuntimeProfile['effort'],
fastMode: intent.fastMode ?? false,
- }, { source: 'user', sessionLockHeld: true, applyingUserSelectionOnSend: applyNow });
+ }, { source: 'user', sessionLockHeld: true, applyingUserSelectionOnSend: applyNow,
+ runtimeSource: intent.runtimeSource, assertSelectionCurrent });
return result;
},
onPendingSwitchChanged: (sessionId, intent) => {
@@ -8790,7 +8794,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
await inputCoordinator.ensureQueueRestored(targetSessionId).catch(() => undefined);
// Private messages and authorization continuations use the durable coordinator, including an idle
// recipient. This preserves input provenance and one recovery/dispatch path.
- if (explicitClientId?.startsWith('bot-dm:') || explicitClientId?.startsWith('bot-authorization-resume:') || inputCoordinator.shouldQueueNewTurn(targetSessionId)) {
+ // Pending selections also need the canonical send transaction: it consumes the intent,
+ // then refreshes queued createOpts from DB before starting the target harness.
+ // enqueue does not await dispatch, so the drain can acquire this lock after we return.
+ if (explicitClientId?.startsWith('bot-dm:') || explicitClientId?.startsWith('bot-authorization-resume:') || inputCoordinator.shouldQueueNewTurn(targetSessionId) || agentSwitchPending.get(targetSessionId)) {
lockStage = 'enqueue-queued-message';
const qClientId = explicitClientId ?? createId();
await enqueueSendToSessionMessage({
@@ -10801,6 +10808,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
type InternalRuntimeSelectionOptions = {
source: 'user' | SessionRuntimeMutationSource;
+ runtimeSource?: 'agent';
+ assertSelectionCurrent?: () => void;
/** Internal calls from the send / switch transaction already own the route lock. */
sessionLockHeld?: boolean;
applyingUserSelectionOnSend?: boolean;
@@ -10990,7 +10999,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
(getSessionEffort(sessionId) as SessionRuntimeProfile['effort']) ?? meta.effort ?? null,
fastMode: live ? getSessionFastMode(sessionId) : meta.fastMode === true,
};
- return { baseline, effective, control };
+ const pendingMutation = pendingHarnessRuntimeMutation(agentSwitchPending.get(sessionId), control.generation)
+ ?? control.pending;
+ return { baseline, effective, control, pendingMutation };
};
const reconcileBotModelRoute = createBotModelRouteReconciler({
@@ -11452,13 +11463,50 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
runtimeGeneration: profiles.control.generation,
baselineProfile: profiles.baseline,
effectiveProfile: profiles.effective,
- pendingMutation: profiles.control.pending,
+ pendingMutation: profiles.pendingMutation,
fallbackEnabled: botFallback.isBot
? botFallback.candidate !== null
: readSessionRuntimeFallbackSettings().enabled,
};
},
setSessionRuntime: async ({ targetSessionId, expectedGeneration, patch }) => {
+ if (patch.harness !== undefined) {
+ return setSessionRuntimeHarness({
+ withSessionLock: withSendToSessionLock,
+ ownerEpoch: captureSessionRuntimeControlOwnerEpoch,
+ generation: (id) => getSessionRuntimeControlSnapshot(id).generation,
+ pendingRevision: (id) => agentSwitchPending.revision!(id),
+ pending: (id) => agentSwitchPending.get(id),
+ read: async (id) => (await readSessionRuntimeProfiles(id))?.effective ?? null,
+ resolve: async (profile, explicit) => {
+ const reroute = await assertModelRouteUsable(profile.agentKind, profile.model, profile.providerId);
+ const providers = await getDesktopProviderService().listProviders({
+ allowSideEffects: false, catalog: getActiveCatalog(),
+ });
+ const providerId = reroute && shouldApplyExclusiveProviderRerouteLive(profile.providerId)
+ ? reroute
+ : profile.providerId ?? effectiveSourceIdForModel(providers, null, profile.model, profile.agentKind);
+ const provider = providers.find((candidate) => candidate.id === providerId);
+ const model = findCatalogModel(provider, profile.model, profile.agentKind, { exact: true });
+ if (!provider?.connected || !model) {
+ throwIpcError('INVALID_PARAMS', `model "${profile.model}" is unavailable for harness "${profile.agentKind}"`);
+ }
+ const axes = resolveSessionRuntimeAxes({
+ model, effort: profile.effort, fastMode: profile.fastMode,
+ effortExplicit: explicit.effort, fastExplicit: explicit.fast,
+ });
+ if (!axes.ok) throwIpcError('INVALID_PARAMS', `target model runtime axes unavailable: ${axes.reason}`);
+ return { ...profile, providerId: providerId ?? null, effort: axes.effort, fastMode: axes.fastMode };
+ },
+ stage: async (id, profile, assertSelectionCurrent) => {
+ return performSessionAgentSwitch(agentSwitchDeps, {
+ sessionId: id, targetAgentKind: profile.agentKind, model: profile.model,
+ providerId: profile.providerId, effort: profile.effort, fastMode: profile.fastMode,
+ runtimeSource: 'agent', assertSelectionCurrent,
+ });
+ },
+ }, { targetSessionId, expectedGeneration, patch: { ...patch, harness: patch.harness } });
+ }
const profiles = await readSessionRuntimeProfiles(targetSessionId);
if (!profiles) {
return {
@@ -15414,6 +15462,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
{ effort: SessionRuntimeProfile['effort']; fastMode: boolean } | undefined;
const runtimeOwnerEpoch = captureSessionRuntimeControlOwnerEpoch();
const assertRuntimeOwnerCurrent = (): void => {
+ internalOptions.assertSelectionCurrent?.();
if (!sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch)) {
throwIpcError(
'PRECONDITION_FAILED',
@@ -15630,6 +15679,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
assertRuntimeOwnerCurrent();
clearPendingCredentialSwitchForSession(sessionId, { wake: false });
const intent = {
+ ...(internalOptions.runtimeSource ? { runtimeSource: internalOptions.runtimeSource } : {}),
sameAgentSelection: true,
targetAgentKind: dbToMakerAgentKind(runtimeStatus.agentKind),
model,
diff --git a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
index 51d76f7390..0f6dfa23d6 100644
--- a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
@@ -113,6 +113,7 @@ export interface MakerSessionAgentSwitchHandlerDeps {
sessionId: string,
intent: PendingAgentSwitchIntent,
applyNow: boolean,
+ assertSelectionCurrent?: () => void,
): Promise<{ deferred: boolean; superseded?: boolean }>;
/** 与 send / SET_MODEL 共用的 session 锁;生产注入,最小测试 harness 可省略。 */
withSessionLock?<T>(sessionId: string, task: () => Promise<T>): Promise<T>;
@@ -240,6 +241,8 @@ export interface SessionAgentSwitchResult {
/** 登记的切换意图(下一条消息发送时刻执行;effort/fastMode 由 renderer 按目标引擎解析好带入)。 */
export interface PendingAgentSwitchIntent {
+ /** Agent-requested complete selection, exposed by the runtime control query. */
+ runtimeSource?: 'agent';
/** SET_MODEL intent: apply the route without a cross-engine handoff. */
sameAgentSelection?: boolean;
targetAgentKind: AgentKind;
@@ -365,6 +368,9 @@ export async function performSessionAgentSwitch(
applyNow?: boolean;
/** Abort signal for direct scheduler/IM sends; checked at side-effect boundaries. */
signal?: AbortSignal;
+ runtimeSource?: 'agent';
+ /** Recheck caller CAS after asynchronous validation, before staging any intent. */
+ assertSelectionCurrent?: () => void;
},
): Promise<SessionAgentSwitchResult> {
const { sessionId, targetAgentKind, model, providerId, signal } = params;
@@ -405,6 +411,9 @@ export async function performSessionAgentSwitch(
if (!row || row.status === 'deleted') {
throwIpcError('NOT_FOUND', `Session ${sessionId} not found`);
}
+ if (params.runtimeSource === 'agent' && row.status === 'archived') {
+ throwIpcError('UNSUPPORTED_CAPABILITY', 'archived task cannot change harness');
+ }
if (row.source === 'review') {
throwIpcError('UNSUPPORTED_CAPABILITY', 'Review task settings are fixed to the source task');
}
@@ -417,6 +426,8 @@ export async function performSessionAgentSwitch(
throwIpcError('UNSUPPORTED_CAPABILITY', 'agent switch is not supported for Orca sessions');
}
+ params.assertSelectionCurrent?.();
+
const fromDbKind: DbAgentKind = normalizeDbAgentKind(row.agentKind);
const toDbKind: DbAgentKind = makerToDbAgentKind(targetAgentKind);
if (fromDbKind === toDbKind) {
@@ -430,7 +441,8 @@ export async function performSessionAgentSwitch(
...(typeof params.effort === 'string' ? { effort: params.effort } : {}),
...(typeof params.fastMode === 'boolean' ? { fastMode: params.fastMode } : {}),
sameAgentSelection: true,
- }, false);
+ ...(params.runtimeSource ? { runtimeSource: params.runtimeSource } : {}),
+ }, false, params.assertSelectionCurrent);
return {
switched: false,
agentKind: targetAgentKind,
@@ -481,6 +493,7 @@ export async function performSessionAgentSwitch(
// 重复登记 = 覆盖(同一意图的最新表达)。
if (!params.applyNow && deps.pendingSwitches) {
const intent: PendingAgentSwitchIntent = {
+ ...(params.runtimeSource ? { runtimeSource: params.runtimeSource } : {}),
targetAgentKind,
model,
providerId: normalizedProviderId,
@@ -634,6 +647,7 @@ export async function performSessionAgentSwitch(
// 清 id 与改边界必须同成同败。失败后重新登记完整意图与恢复载荷,
// 下一条消息先重试原子恢复尾段,而不是带半状态继续 lazy-create。
deps.pendingSwitches?.set(sessionId, {
+ ...(params.runtimeSource ? { runtimeSource: params.runtimeSource } : {}),
targetAgentKind,
model,
providerId: normalizedProviderId,
@@ -657,6 +671,7 @@ export async function performSessionAgentSwitch(
// 边界插入失败时无法原子保证“清 id + 改边界”。保留意图自愈,
// 避免只清 sdk id 后 DB pending 与实际注入内容分叉。
deps.pendingSwitches?.set(sessionId, {
+ ...(params.runtimeSource ? { runtimeSource: params.runtimeSource } : {}),
targetAgentKind,
model,
providerId: normalizedProviderId,
@@ -730,7 +745,8 @@ export async function performSessionAgentSwitch(
* send 事务既有的 SESSION_RUNNING guard / coordinator 重试;
* - 空闲 → 执行完整切换事务(skipBootstrap:随后的 lazy-create 会按 DB 新值
* spawn),成功后才以 CAS 清 pending;
- * - 执行失败不阻塞发送,但保留原意图,下一条消息自动重试。resume 回落事务
+ * - 完整 Agent 选择或同引擎模型选择失败时阻止发送并保留意图;旧跨引擎选择器
+ * 保留原有失败后继续发送的行为。resume 回落事务
* 已进入 commit point 后若失败,则只重试其原子恢复尾段。
*/
const pendingAgentSwitchApplyInFlight = new Map<string, Promise<void>>();
@@ -795,6 +811,7 @@ export function applyPendingAgentSwitchIfIdle(
const result = await performSessionAgentSwitch(deps, {
sessionId,
targetAgentKind: intent.targetAgentKind,
+ runtimeSource: intent.runtimeSource,
model: intent.model,
providerId: intent.providerId,
effort: intent.effort,
@@ -806,6 +823,9 @@ export function applyPendingAgentSwitchIfIdle(
applyNow: true,
signal: opts?.signal,
});
+ if (result.retryPending && intent.runtimeSource === 'agent') {
+ throw new Error('Harness switch recovery is pending; retry the send after recovery');
+ }
// CAS 语义:执行期间用户可能又选了另一个目标,不能把新意图一起清掉。
if (!result.retryPending && deps.pendingSwitches?.get(sessionId) === intent) {
deps.pendingSwitches.clear(sessionId);
@@ -823,7 +843,7 @@ export function applyPendingAgentSwitchIfIdle(
err: err instanceof Error ? err.message : String(err),
});
// Never send on the old model after the user's selected route failed preparation.
- if (intent.sameAgentSelection) throw err;
+ if (intent.sameAgentSelection || intent.runtimeSource === 'agent') throw err;
}
})().finally(() => {
if (pendingAgentSwitchApplyInFlight.get(sessionId) === run) {
diff --git a/apps/desktop/src/main/maker-ipc/sessionControlService.ts b/apps/desktop/src/main/maker-ipc/sessionControlService.ts
index 62def3dcd0..eb40c9d84f 100644
--- a/apps/desktop/src/main/maker-ipc/sessionControlService.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionControlService.ts
@@ -57,6 +57,7 @@ export type SessionRuntimeSetResult =
| {
ok: true;
status: 'applied' | 'deferred';
+ effectiveBoundary?: 'next_send';
generation: number;
effectiveProfile: SessionRuntimeProfile;
pendingMutation: PendingSessionRuntimeMutation | null;
@@ -86,6 +87,7 @@ export interface SessionControlServiceDeps {
targetSessionId: string;
expectedGeneration?: number;
patch: {
+ harness?: AgentKind;
model?: string;
providerId?: string | null;
effort?: Effort;
@@ -280,6 +282,7 @@ export function createSessionControlService(deps: SessionControlServiceDeps) {
targetSessionId: string;
expectedGeneration?: number;
patch: {
+ harness?: AgentKind;
model?: string;
providerId?: string | null;
effort?: Effort;
diff --git a/apps/desktop/src/main/maker-ipc/sessionRuntimeHarnessSelection.ts b/apps/desktop/src/main/maker-ipc/sessionRuntimeHarnessSelection.ts
new file mode 100644
index 0000000000..0e423c31a4
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/sessionRuntimeHarnessSelection.ts
@@ -0,0 +1,143 @@
+import type { AgentKind, Effort } from '@cindy/maker-core';
+import type { SessionRuntimeSetResult } from './sessionControlService.js';
+import type { PendingAgentSwitchIntent } from './sessionAgentSwitchHandler.js';
+import type {
+ PendingSessionRuntimeMutation,
+ SessionRuntimeProfile,
+} from './sessionRuntimeControl.js';
+
+export function pendingHarnessRuntimeMutation(
+ intent: PendingAgentSwitchIntent | undefined,
+ generation: number,
+): PendingSessionRuntimeMutation | null {
+ if (intent?.runtimeSource !== 'agent') return null;
+ return {
+ generation,
+ source: 'agent',
+ profile: {
+ agentKind: intent.targetAgentKind,
+ model: intent.model,
+ providerId: intent.providerId ?? null,
+ effort: (intent.effort ?? null) as Effort | null,
+ fastMode: intent.fastMode === true,
+ },
+ };
+}
+
+export interface HarnessRuntimeSelectionDeps {
+ withSessionLock<T>(sessionId: string, run: () => Promise<T>): Promise<T>;
+ ownerEpoch(): string;
+ generation(sessionId: string): number;
+ pendingRevision(sessionId: string): number;
+ read(sessionId: string): Promise<SessionRuntimeProfile | null>;
+ resolve(
+ profile: SessionRuntimeProfile,
+ explicit: { effort: boolean; fast: boolean },
+ ): Promise<SessionRuntimeProfile>;
+ stage(
+ sessionId: string,
+ profile: SessionRuntimeProfile,
+ assertCurrent: () => void,
+ ): Promise<{ deferred?: boolean; sameEngineSuperseded?: boolean }>;
+ pending(sessionId: string): PendingAgentSwitchIntent | undefined;
+}
+
+/** Complete selections share the picker/send transaction, never the turn-end override queue. */
+export async function setSessionRuntimeHarness(
+ deps: HarnessRuntimeSelectionDeps,
+ params: {
+ targetSessionId: string;
+ expectedGeneration?: number;
+ patch: {
+ harness: AgentKind;
+ model?: string;
+ providerId?: string | null;
+ effort?: Effort;
+ fastMode?: boolean;
+ };
+ },
+): Promise<SessionRuntimeSetResult> {
+ const { targetSessionId: id, expectedGeneration, patch } = params;
+ if (!['claude-code', 'codex', 'pi'].includes(patch.harness) || !patch.model?.trim()) {
+ return {
+ ok: false,
+ errorCode: 'INVALID_ARGS',
+ message: 'harness requires a valid target harness and model',
+ };
+ }
+ const owner = deps.ownerEpoch();
+ try {
+ return await deps.withSessionLock(id, async () => {
+ const revision = deps.pendingRevision(id);
+ const assertCurrent = () => {
+ if (
+ expectedGeneration === undefined ||
+ deps.ownerEpoch() !== owner ||
+ deps.generation(id) !== expectedGeneration ||
+ deps.pendingRevision(id) !== revision
+ ) {
+ throw Object.assign(
+ new Error('session runtime changed; read get_session_runtime again before retrying'),
+ { code: 'CONFLICT' },
+ );
+ }
+ };
+ assertCurrent();
+ const effective = await deps.read(id);
+ if (!effective)
+ return { ok: false, errorCode: 'NOT_FOUND', message: `session ${id} not found` };
+ const profile = await deps.resolve(
+ {
+ agentKind: patch.harness,
+ model: patch.model!,
+ // Never inherit an old harness's provider when selecting a new target.
+ providerId: patch.providerId ?? null,
+ effort: patch.effort ?? effective.effort,
+ fastMode: patch.fastMode ?? effective.fastMode,
+ },
+ { effort: patch.effort !== undefined, fast: patch.fastMode !== undefined },
+ );
+ assertCurrent();
+ const result = await deps.stage(id, profile, assertCurrent);
+ if (result.sameEngineSuperseded) {
+ return {
+ ok: false,
+ errorCode: 'CONFLICT',
+ message: 'session selection was superseded; read its runtime again',
+ };
+ }
+ if (!result.deferred) {
+ return {
+ ok: false,
+ errorCode: 'ROUTE_UNAVAILABLE',
+ message: 'session selection could not be staged',
+ };
+ }
+ const generation = deps.generation(id);
+ return {
+ ok: true,
+ status: 'deferred',
+ effectiveBoundary: 'next_send',
+ generation,
+ effectiveProfile: effective,
+ pendingMutation: pendingHarnessRuntimeMutation(deps.pending(id), generation),
+ };
+ });
+ } catch (error) {
+ const code = (error as { code?: string }).code;
+ if (
+ code === 'CONFLICT' ||
+ code === 'NOT_FOUND' ||
+ code === 'INVALID_PARAMS' ||
+ code === 'UNSUPPORTED_CAPABILITY' ||
+ code === 'CREDENTIAL_SWITCH_BUSY'
+ ) {
+ return {
+ ok: false,
+ errorCode: code === 'CONFLICT' || code === 'NOT_FOUND' ? code : 'ROUTE_UNAVAILABLE',
+ message: error instanceof Error ? error.message : String(error),
+ };
+ }
+ throw error;
+ }
+}
diff --git a/docs/product-rules/session-runtime-control.md b/docs/product-rules/session-runtime-control.md
index 97f9202add..96e95c406d 100644
--- a/docs/product-rules/session-runtime-control.md
+++ b/docs/product-rules/session-runtime-control.md
@@ -12,7 +12,7 @@ Cindy 允许 Agent 通过统一会话控制面查询和临时调整当前任务
- `baseline`:用户保存到任务记录的模型、来源、推理强度与 Fast。
- `effective`:当前实际生效的运行时组合;Agent 临时切换和自动降级只改这一层。
-- `pending`:任务忙碌时已接受、等待当前 turn 结束的运行时组合。
+- `pending`:已接受但尚未生效的组合;临时调整等当前 turn 结束,显式 Harness 选择等下一条消息发送。
- `generation`:运行时控制面的单调版本。跨任务修改应先读后写并携带 generation,避免旧请求覆盖新选择。
用户在模型选择器中的完整选择会清除临时运行时组合;用户单独修改推理强度或 Fast 时,
@@ -24,8 +24,16 @@ Cindy 允许 Agent 通过统一会话控制面查询和临时调整当前任务
effective、pending、generation 和自动降级开关。
- `set_session_runtime`:`session_id` 可省略;原子提交来源、模型、推理强度与 Fast 的任意子集。
- 当前或目标任务忙碌时不修改进行中的 turn,返回 `deferred`,在下一个 turn 边界生效。
-- 不允许借此切换 Harness;跨 Harness 仍走独立的人机切换流程。
-- Agent 的修改不写回任务 baseline。语义失败是否提高推理强度或换更强模型,由 Agent 或 Skill 明确请求。
+- 省略 `harness` 时,Agent 的修改不写回任务 baseline。语义失败是否提高推理强度或换更强模型,由 Agent 或 Skill 明确请求。
+- 显式提供 `harness`(`claude-code` / `codex` / `pi`)时必须同时指定 `model`,表示完整的任务执行选择;
+ 即使选回当前 Harness,也复用模型选择器的完整选择语义。目标模型、来源、推理强度和 Fast 在登记前一起校验,
+ 省略来源时按目标 Harness 的模型解析默认来源,不沿用旧 Harness 的来源。
+- 完整选择返回 `deferred` / `effective_boundary: next_send`,清除此前临时调整;`get_session_runtime.pending`
+ 显示目标 Harness,`effective` 仍表示当前运行组合。空闲和忙碌任务均在下一条消息发送时消费意图,
+ 复用现有历史交接与原生绑定切换事务,更新该任务 baseline,但不修改全局默认设置。
+ 切换失败时保留待切换选择并阻止该次发送,不继续使用旧引擎。
+- SSH 远程、Orca、Review 和归档任务不支持此完整选择。存在待切换 Harness 时如需修改目标,
+ 重新读取 generation 并再次提交完整 `harness` + `model`;普通临时调整不会覆盖待切换选择。
## 自动降级
diff --git a/packages/lizi-mcps/src/__tests__/sessionControlTools.test.ts b/packages/lizi-mcps/src/__tests__/sessionControlTools.test.ts
index ed3830c62e..7b22940448 100644
--- a/packages/lizi-mcps/src/__tests__/sessionControlTools.test.ts
+++ b/packages/lizi-mcps/src/__tests__/sessionControlTools.test.ts
@@ -80,6 +80,30 @@ function setup(opts?: { sessionId?: string | undefined }) {
}
describe('cindy_helper session control tools', () => {
+ it('forwards a complete harness selection and reports the next-send boundary', async () => {
+ const { deps, registry } = setup();
+ const old = { agentKind: 'claude-code' as const, model: 'claude-fable-5', providerId: null, effort: 'high' as const, fastMode: false };
+ vi.mocked(deps.setSessionRuntime).mockResolvedValueOnce({
+ ok: true, status: 'deferred', effectiveBoundary: 'next_send', generation: 2,
+ effectiveProfile: old,
+ pendingMutation: { generation: 2, source: 'agent', profile: { ...old, agentKind: 'codex', model: 'gpt-6-astra', providerId: 'openai' } },
+ });
+ expect(parse(await registry.call('set_session_runtime', {
+ session_id: 'target', harness: 'codex', model: 'gpt-6-astra', provider_id: 'openai', expected_generation: 1,
+ }))).toMatchObject({
+ ok: true, effective_boundary: 'next_send', effective: { harness: 'claude-code' },
+ pending: { profile: { harness: 'codex', model: 'gpt-6-astra' } },
+ });
+ expect(deps.setSessionRuntime).toHaveBeenCalledWith({ targetSessionId: 'target', expectedGeneration: 1,
+ patch: { harness: 'codex', model: 'gpt-6-astra', providerId: 'openai' } });
+ });
+
+ it.each([{ harness: 'codex' }, { harness: 'unknown', model: 'gpt-6-astra' }])('rejects invalid complete selection %j', async (patch) => {
+ const { deps, registry } = setup();
+ expect(parse(await registry.call('set_session_runtime', { ...patch, expected_generation: 1 }))).toMatchObject({ ok: false, errorCode: 'INVALID_ARGS' });
+ expect(deps.setSessionRuntime).not.toHaveBeenCalled();
+ });
+
it('atomically changes the current session runtime with generation CAS', async () => {
const { deps, registry } = setup();
const result = parse(
diff --git a/packages/lizi-mcps/src/xdt-helper/session_control.ts b/packages/lizi-mcps/src/xdt-helper/session_control.ts
index d67b1a23c4..6194d056df 100644
--- a/packages/lizi-mcps/src/xdt-helper/session_control.ts
+++ b/packages/lizi-mcps/src/xdt-helper/session_control.ts
@@ -80,6 +80,7 @@ export interface SessionControlDeps {
targetSessionId: string;
expectedGeneration?: number;
patch: {
+ harness?: AgentKind;
model?: string;
providerId?: string | null;
effort?: Effort;
@@ -89,6 +90,7 @@ export interface SessionControlDeps {
ControlResult<
{
status: 'applied' | 'deferred';
+ effectiveBoundary?: 'next_send';
generation: number;
effectiveProfile: SessionRuntimeProfile;
pendingMutation: SessionRuntimeSnapshot['pendingMutation'];
@@ -314,9 +316,11 @@ export function registerSetSessionRuntimeTool(
category: 'control',
description:
'原子调整当前或指定本机任务的模型来源、模型、推理强度与 Fast。省略 session_id 时作用于当前任务;' +
- '忙碌任务在当前 turn 结束后生效。先用 get_session_runtime 读取 generation,再用 expected_generation 防止覆盖并发修改。' +
- '不切换 harness,不修改用户保存的默认选择。',
+ '临时调整在忙碌任务的当前 turn 结束后生效。先用 get_session_runtime 读取 generation,再用 expected_generation 防止覆盖并发修改。' +
+ '提供 harness 时必须同时指定 model:完整选择会保存到目标任务,并在下一条消息发送时切换(返回 next_send);' +
+ '省略 harness 保持临时调整语义。不修改全局默认选择。',
inputShape: {
+ harness: z.enum(['claude-code', 'codex', 'pi']).optional().describe('目标执行引擎;提供时必须同时指定 model。'),
session_id: z.string().min(1).optional().describe('目标 session id;省略时使用当前任务。'),
provider_id: z
.string()
@@ -335,11 +339,14 @@ export function registerSetSessionRuntimeTool(
'必填:先调用 get_session_runtime 读取当前 generation 并原样传回,用于防止覆盖并发修改。',
),
},
- handler: async ({ session_id, provider_id, model, effort, fast, expected_generation }) => {
+ handler: async ({ session_id, harness, provider_id, model, effort, fast, expected_generation }) => {
const targetSessionId = session_id ?? requireCallerSession(deps);
if (!targetSessionId) {
return errorPayload('NO_SESSION_CONTEXT', '当前 MCP 调用没有绑定 session,请显式提供 session_id。');
}
+ if (harness !== undefined && !model?.trim()) {
+ return errorPayload('INVALID_ARGS', '提供 harness 时必须同时指定目标 model。');
+ }
if (
provider_id === undefined &&
model === undefined &&
@@ -356,6 +363,7 @@ export function registerSetSessionRuntimeTool(
targetSessionId,
expectedGeneration: expected_generation,
patch: {
+ ...(harness !== undefined ? { harness } : {}),
...(provider_id !== undefined ? { providerId: provider_id } : {}),
...(model !== undefined ? { model } : {}),
...(effort !== undefined ? { effort } : {}),
@@ -375,7 +383,7 @@ export function registerSetSessionRuntimeTool(
profile: runtimeProfilePayload(result.pendingMutation.profile),
}
: null,
- effective_boundary: result.status === 'deferred' ? 'next_turn' : 'immediate',
+ effective_boundary: result.effectiveBoundary ?? (result.status === 'deferred' ? 'next_turn' : 'immediate'),
});
},
});