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: keep runtime axes with pending user model selections

Dashc8ea78a94aaa
diff --git a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
index b7f0cfcfa6..6c3492e78c 100644
--- a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
+++ b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
@@ -47,9 +47,19 @@ function handlerBody(source: string, channel: string, nextChannel: string): stri
// an archived row plus a remote effort/Fast write is the minimal regression.
const axisHandlers = new Map<string, string>();
const registerAst = ts.createSourceFile('register.ts', registerSource, ts.ScriptTarget.Latest, true);
+// Compile only the production predicate; importing its runtime module here
+// would load the entire harness dependency chain into this fast guard suite.
+const switchAst = ts.createSourceFile('sessionAgentSwitchHandler.ts', readFileSync(
+ resolve(mainRoot, 'maker-ipc/sessionAgentSwitchHandler.ts'), 'utf8'), ts.ScriptTarget.Latest, true);
+const userIntentPredicate = switchAst.statements.find((node): node is ts.FunctionDeclaration =>
+ ts.isFunctionDeclaration(node) && node.name?.text === 'isUserPendingAgentSwitchIntent')!;
+const isUserPendingAgentSwitchIntent = new Function(ts.transpileModule(
+ `return (intent) => ${userIntentPredicate.body!.getText(switchAst)};`,
+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } },
+).outputText)();
function collectAxisHandlers(node: ts.Node): void {
if (ts.isVariableDeclaration(node) && node.initializer &&
- ['applyEffort', 'applyFastMode'].includes(node.name.getText(registerAst))) {
+ ['applyEffort', 'applyFastMode', 'stagePendingUserRuntimeAxis'].includes(node.name.getText(registerAst))) {
axisHandlers.set(node.name.getText(registerAst), ts.transpileModule(
`return ${node.initializer.getText(registerAst)};`,
{ compilerOptions: { target: ts.ScriptTarget.ES2022 } },
@@ -76,11 +86,16 @@ describe.each([
remoteResponse: response, [persistName]: persist, agentSwitchPending: pending,
assertOwnerCurrent: vi.fn(), assertSharedTaskCurrent: { admit: vi.fn() },
markRemoteSettingPersistedInsideHandler: vi.fn(), maker: { getSession },
- agentSwitchDeps: { selectSameAgentModel: async (id: string, intent: unknown) => { pending.set(id, intent); } },
+ isUserPendingAgentSwitchIntent, projectPendingAgentSwitchIntent: (intent: unknown) => intent,
+ wakeSessionInputAfterCredentialSwitch: vi.fn(),
+ agentSwitchDeps: { selectSameAgentModel: async (id: string, intent: unknown) => { pending.set(id, intent); },
+ onPendingSwitchChanged: vi.fn() },
throwIpcError: (code: string, message: string) => { throw new Error(`[${code}] ${message}`); },
};
- const run = new Function(...Object.keys(bindings), axisHandlers.get(handler)!)(...Object.values(bindings));
- return { run, row, persist, response, getSession, pending };
+ const stagePendingUserRuntimeAxis = new Function(...Object.keys(bindings), axisHandlers.get('stagePendingUserRuntimeAxis')!)(...Object.values(bindings));
+ const runBindings = { ...bindings, stagePendingUserRuntimeAxis };
+ const run = new Function(...Object.keys(runBindings), axisHandlers.get(handler)!)(...Object.values(runBindings));
+ return { run, row, persist, response, getSession, pending, changed: bindings.agentSwitchDeps.onPendingSwitchChanged };
}
it('acknowledges the saved axis while the task stays archived and the runtime stays untouched', async () => {
@@ -91,16 +106,34 @@ describe.each([
expect(h.getSession).not.toHaveBeenCalled();
});
- it('updates an already selected model instead of writing its axis onto the old route', async () => {
+ it.each(['same-agent', 'cross-engine', 'relocation'] as const)('updates the selected %s model instead of the old route', async kind => {
const h = setup('archived');
- h.pending.set('archived-task', { sameAgentSelection: true, model: 'next-model' });
+ const intent = { targetAgentKind: kind === 'cross-engine' ? 'pi' : 'codex', model: 'next-model',
+ providerId: 'next-provider', effort: 'low', fastMode: false, confirmedContextWindow: 200000,
+ ...(kind === 'same-agent' ? { sameAgentSelection: true } : {}),
+ ...(kind === 'relocation' ? { targetAgentDeviceId: 'other-device' } : {}),
+ };
+ h.pending.set('archived-task', intent);
await h.run();
- expect(h.pending.get('archived-task')).toMatchObject({ model: 'next-model', [field]: value });
+ expect(h.pending.get('archived-task')).toEqual({ ...intent, [field]: value });
+ if (kind !== 'same-agent') expect(h.changed).toHaveBeenCalledWith('archived-task',
+ expect.objectContaining({ model: 'next-model', [field]: value }));
expect(h.row).toMatchObject({ status: 'archived', effort: 'low', fastMode: false });
expect(h.persist).not.toHaveBeenCalled();
expect(h.getSession).not.toHaveBeenCalled();
});
+ it.each([{ configStaged: true }, { runtimeSource: 'agent' }])('keeps automatic intent %j separate from user axis writes', async source => {
+ const h = setup('archived');
+ const intent = { sameAgentSelection: true, model: 'automatic-model', ...source };
+ h.pending.set('archived-task', intent);
+ await h.run();
+ expect(h.pending.get('archived-task')).toBe(intent);
+ expect(h.row).toMatchObject({ status: 'archived', [field]: value });
+ expect(h.persist).toHaveBeenCalledOnce();
+ expect(h.getSession).not.toHaveBeenCalled();
+ });
+
it('rejects a deleted task before saving anything', async () => {
const h = setup('deleted');
await expect(h.run()).rejects.toThrow('PRECONDITION_FAILED');
@@ -938,7 +971,7 @@ describe('session runtime control wiring', () => {
expect(body).toContain('return withSendToSessionLock(sessionId');
expect(body).toContain("runtimeStatus.status !== 'active' && runtimeStatus.status !== 'archived'");
const archiveStart = body.indexOf("if (runtimeStatus.status === 'archived')");
- expect(archiveStart).toBeGreaterThan(body.indexOf('if (userIntent?.sameAgentSelection)'));
+ expect(archiveStart).toBeGreaterThan(body.indexOf('if (isUserPendingAgentSwitchIntent(userIntent))'));
const archiveEnd = body.indexOf('const livePatch:', archiveStart);
const archive = body.slice(archiveStart, archiveEnd);
expect(archive).toContain(`await ${persist}();`);
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.ts
index ec7de33c02..edf0b2ca5a 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.ts
@@ -1,7 +1,7 @@
import { readFileSync } from 'node:fs';
import ts from 'typescript';
import { describe, expect, it, vi } from 'vitest';
-import { applyPendingAgentSwitchIfIdle, createPendingAgentSwitchRegistry, type MakerSessionAgentSwitchHandlerDeps, type PendingAgentSwitchIntent } from '../sessionAgentSwitchHandler';
+import { applyPendingAgentSwitchIfIdle, createPendingAgentSwitchRegistry, isUserPendingAgentSwitchIntent, type MakerSessionAgentSwitchHandlerDeps, type PendingAgentSwitchIntent } from '../sessionAgentSwitchHandler';
import { parseOrcaRemoteLead } from '../../../shared/orcaRemoteWorker';
// Execute the actual picker admission branches (local and agent-device), with
@@ -15,7 +15,11 @@ let piWindowOverride = '';
let directSendAdapter = '';
let archivedAdmission = '';
let terminalGuard = '';
+let stageAxisAdapter = '';
function visit(node: ts.Node) {
+ if (ts.isVariableDeclaration(node) && node.name.getText(source) === 'stagePendingUserRuntimeAxis') {
+ stageAxisAdapter = node.initializer!.getText(source);
+ }
if (ts.isBinaryExpression(node) && node.left.getText(source) === 'pendingAgentSwitchApplyHolder') {
directSendAdapter = node.right.getText(source);
}
@@ -58,7 +62,7 @@ describe('Orca model-only picker intent admission', () => {
const js = ts.transpileModule(`return ${expression};`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
return new Function(...Object.keys(bindings), js)(...Object.values(bindings));
};
- const row = { id: 's1', status: 'archived', agentKind: 'codex', model: 'old', providerId: 'provider',
+ const row = { id: 's1', status: 'archived', agentKind: 'codex', model: 'old', providerId: 'provider', effort: 'low', fastMode: false,
sdkSessionId: null, remoteHostId: null, agentDeviceId: null };
const pending = createPendingAgentSwitchRegistry();
const crossEngine = mode === 'cross-engine' || mode === 'repicked-during-restore';
@@ -99,8 +103,15 @@ describe('Orca model-only picker intent admission', () => {
const directSend = compile(directSendAdapter, {
agentSwitchPending: pending, restoreArchivedSessionForSend: restore,
acquireSendToSessionLock: acquire, reconcileBotModelRoute: vi.fn(),
- applyPendingAgentSwitchIfIdle, agentSwitchDeps: deps, contextOverflowRolloverHolder: null,
+ applyPendingAgentSwitchIfIdle, isUserPendingAgentSwitchIntent, agentSwitchDeps: deps, contextOverflowRolloverHolder: null,
});
+ if (mode === 'cross-engine' || mode === 'relocation') {
+ const stageAxis = compile(stageAxisAdapter, { agentSwitchPending: pending, agentSwitchDeps: deps,
+ projectPendingAgentSwitchIntent: (intent: unknown) => intent, wakeSessionInputAfterCredentialSwitch: vi.fn() });
+ await stageAxis('s1', pending.get('s1'), { effort: 'high' });
+ await stageAxis('s1', pending.get('s1'), { fastMode: true });
+ expect(row).toMatchObject({ status: 'archived', model: 'old', effort: 'low', fastMode: false });
+ }
const controller = new AbortController();
if (mode === 'cancelled') controller.abort();
if (automatic) {
@@ -127,6 +138,7 @@ describe('Orca model-only picker intent admission', () => {
expect(row.model).toBe(mode === 'repicked-during-restore' ? 'latest' : 'new');
expect(row.agentKind).toBe(mode === 'relocation' ? 'codex' : 'pi');
if (mode === 'relocation') expect(row.agentDeviceId).toBe('executor-device');
+ if (mode === 'cross-engine' || mode === 'relocation') expect(row).toMatchObject({ effort: 'high', fastMode: true });
}
expect(pending.get('s1')).toBeUndefined();
expect(restore.mock.invocationCallOrder[0]).toBeLessThan(acquire.mock.invocationCallOrder[0]);
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index d3c1cf3355..d9ded32c74 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -1010,12 +1010,14 @@ import {
import {
applyPendingAgentSwitchIfIdle,
createPendingAgentSwitchRegistry,
+ isUserPendingAgentSwitchIntent,
performSessionAgentSwitch,
projectPendingAgentSwitchIntent,
registerMakerSessionAgentSwitchHandler,
relocateForFreshStart,
settleSystemRouteSwitchIntent,
type MakerSessionAgentSwitchHandlerDeps,
+ type PendingAgentSwitchIntent,
} from './sessionAgentSwitchHandler.js';
import { pendingHarnessRuntimeMutation, setSessionRuntimeHarness } from './sessionRuntimeHarnessSelection.js';
import {
@@ -10437,8 +10439,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// The restore owns the same route lock, so run it before acquiring the
// direct-send lease (which is deliberately held until the caller sends).
const pendingSelection = agentSwitchPending.get(sessionId);
- if (!signal?.aborted && pendingSelection &&
- pendingSelection.runtimeSource !== 'agent' && pendingSelection.configStaged !== true) {
+ if (!signal?.aborted && isUserPendingAgentSwitchIntent(pendingSelection)) {
await restoreArchivedSessionForSend(sessionId);
}
let stage = 'direct-send:acquire';
@@ -22132,6 +22133,24 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
};
+ // Called under the existing send lock after owner/shared-task admission.
+ // Keep the selected route intact: cross-engine/device intents must not pass
+ // through SET_MODEL, which would reinterpret them as the current harness.
+ const stagePendingUserRuntimeAxis = async (
+ sessionId: string,
+ intent: PendingAgentSwitchIntent,
+ patch: Pick<PendingAgentSwitchIntent, 'effort' | 'fastMode'>,
+ ) => {
+ const updated = { ...intent, ...patch };
+ if (intent.sameAgentSelection) {
+ return agentSwitchDeps.selectSameAgentModel!(sessionId, updated, false);
+ }
+ agentSwitchPending.set(sessionId, updated);
+ agentSwitchDeps.onPendingSwitchChanged?.(sessionId, projectPendingAgentSwitchIntent(updated));
+ wakeSessionInputAfterCredentialSwitch(sessionId);
+ return { deferred: true, pendingUntilSend: true };
+ };
+
ipcMain.handle(MAKER_INVOKE.SET_EFFORT, async (event, sessionId: unknown, effort: unknown) => {
// 轮 24-I3 HIGH:会话变更型 IPC 统一 sender 校验(对齐 SET_PERMISSION_MODE)——
// 任意 WebView/受污染页面不得修改活会话偏好。device-link 远程控制端已授权。
@@ -22178,11 +22197,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
);
}
const userIntent = agentSwitchPending.get(sessionId);
- if (userIntent?.sameAgentSelection) {
+ if (isUserPendingAgentSwitchIntent(userIntent)) {
assertOwnerCurrent();
assertSharedTaskCurrent.admit();
- const result = await agentSwitchDeps.selectSameAgentModel!(sessionId,
- { ...userIntent, effort: effort }, false);
+ const result = await stagePendingUserRuntimeAxis(sessionId, userIntent, { effort });
if (remoteResponse) markRemoteSettingPersistedInsideHandler(remoteResponse);
return remoteResponse ?? result;
}
@@ -22708,11 +22726,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
);
}
const userIntent = agentSwitchPending.get(sessionId);
- if (userIntent?.sameAgentSelection) {
+ if (isUserPendingAgentSwitchIntent(userIntent)) {
assertOwnerCurrent();
assertSharedTaskCurrent.admit();
- const result = await agentSwitchDeps.selectSameAgentModel!(sessionId,
- { ...userIntent, fastMode: enabled }, false);
+ const result = await stagePendingUserRuntimeAxis(sessionId, userIntent, { fastMode: enabled });
if (remoteResponse) markRemoteSettingPersistedInsideHandler(remoteResponse);
return remoteResponse ?? result;
}
diff --git a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
index c284af6d5b..2815f258cc 100644
--- a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
@@ -394,6 +394,13 @@ export interface PendingAgentSwitchIntent {
};
}
+/** 用户 picker 意图的统一来源判据;引擎与执行电脑是否改变不影响归属。 */
+export function isUserPendingAgentSwitchIntent(
+ intent: PendingAgentSwitchIntent | undefined,
+): intent is PendingAgentSwitchIntent {
+ return !!intent && intent.configStaged !== true && intent.runtimeSource !== 'agent';
+}
+
/** 控制端可见的 pending intent 投影;刻意排除 main 内部恢复载荷。 */
export interface PublicAgentSwitchIntent {
targetAgentKind: AgentKind;
@@ -1166,7 +1173,7 @@ async function noteLandedUserRouteSelection(
sessionId: string,
intent: PendingAgentSwitchIntent,
): Promise<void> {
- if (intent.configStaged === true || intent.runtimeSource === 'agent') return;
+ if (!isUserPendingAgentSwitchIntent(intent)) return;
try {
await deps.onUserRouteSelectionLanded?.(sessionId);
} catch (err) {
diff --git a/docs/dev-rules/model-catalog-runtime.md b/docs/dev-rules/model-catalog-runtime.md
index 3a2480fd6a..36774f3748 100644
--- a/docs/dev-rules/model-catalog-runtime.md
+++ b/docs/dev-rules/model-catalog-runtime.md
@@ -52,7 +52,8 @@ thread 配置,同时设置窗口和 90% 自动压缩预算,保留原生 5%
归档任务允许用户调整模型、推理强度与 Fast,不要求先恢复,也不因设置变化恢复任务。
模型选择沿用活动任务的暂存意图,下一次发送(含 Goal 直发)先经普通任务恢复入口恢复
任务再应用;受管任务的恢复限制保持不变。暂存意图仍只在被控端
-内存中保留,不新增跨进程恢复。已有模型意图时,推理强度与 Fast 更新该意图;否则
+内存中保留,不新增跨进程恢复。已有用户模型意图时,无论同引擎、跨引擎或换执行电脑,
+推理强度与 Fast 都更新完整待选意图,保留目标路由和窗口确认,不改写自动意图;否则
只保存任务字段,不重建归档时清掉的 runtime 状态。自动模型变更与已删除任务仍拒绝。
本机桌面、设备互联与手机共用此处理,见 `maker-ipc/register.ts` 和
`sessionRuntimeControlWiring.test.ts` 与 `orcaModelSelectionIntent.test.ts` 的归档生命周期回归。