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: 按暂存目标路由校验思考强度和 Fast

Dash81dc080f314b
diff --git a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
index 5ab962cbd6..1c44b1d8f8 100644
--- a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
+++ b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
@@ -104,7 +104,13 @@ describe.each([
markRemoteSettingPersistedInsideHandler: vi.fn(), maker: { getSession },
isUserPendingAgentSwitchIntent, projectPendingAgentSwitchIntent: (intent: unknown) => intent,
wakeSessionInputAfterCredentialSwitch: vi.fn(),
- agentSwitchDeps: { selectSameAgentModel: async (id: string, intent: unknown) => { pending.set(id, intent); },
+ getActiveCatalog: () => ({}),
+ getDesktopProviderService: () => ({ listProviders: async () => [{ id: 'next-provider', connected: true }] }),
+ readUsableAgentDeviceProviders: async () => [{ id: 'next-provider', connected: true }],
+ effectiveSourceIdForModel: () => 'next-provider', findCatalogModel: () => ({}),
+ resolveSessionRuntimeAxes: (axes: object) => ({ ok: true, ...axes }),
+ agentSwitchDeps: { getSessionRow: async () => row,
+ selectSameAgentModel: async (id: string, intent: unknown) => { pending.set(id, intent); },
onPendingSwitchChanged: vi.fn() },
throwIpcError: (code: string, message: string) => { throw new Error(`[${code}] ${message}`); },
};
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 30d5ce5731..fe7906f5db 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.ts
@@ -4,6 +4,8 @@ import { describe, expect, it, vi } from 'vitest';
import { applyPendingAgentSwitchIfIdle, createPendingAgentSwitchRegistry, isUserPendingAgentSwitchIntent, type MakerSessionAgentSwitchHandlerDeps, type PendingAgentSwitchIntent } from '../sessionAgentSwitchHandler';
import { parseOrcaRemoteLead } from '../../../shared/orcaRemoteWorker';
import { acquireSendToSessionLock, withSendToSessionLock } from '../sendToSessionLock';
+import { effectiveSourceIdForModel, findCatalogModel, type ProviderView } from '@cindy/model-providers';
+import { resolveSessionRuntimeAxes } from '../sessionRuntimeControl';
// Execute the actual picker admission branches (local and agent-device), with
// everything after admission represented by applyLive. No Electron bootstrap.
@@ -58,6 +60,82 @@ function compile(expression: string, bindings: Record<string, unknown>) {
return new Function(...Object.keys(bindings), js)(...Object.values(bindings));
}
+function axisCatalogBindings(row: object = {}) {
+ const models = ['target', 'new'].map(id => ({ id, name: id, mode: 'chat', efforts: ['low', 'high'], defaultEffort: 'low', supportsFastMode: true }));
+ const providers = [{ id: 'provider', connected: true, agents: ['codex', 'pi'], routing: { codex: {}, pi: {} },
+ models: { codex: models, pi: models } }] as unknown as ProviderView[];
+ return {
+ effectiveSourceIdForModel, findCatalogModel, resolveSessionRuntimeAxes,
+ getActiveCatalog: () => ({}),
+ getDesktopProviderService: () => ({ listProviders: async () => providers }),
+ readUsableAgentDeviceProviders: vi.fn(async () => providers),
+ agentSwitchDeps: { getSessionRow: async () => row },
+ throwIpcError: (code: string, message: string) => { throw new Error(`[${code}] ${message}`); },
+ };
+}
+
+// Unit: stale UI axes must be admitted against the pending execution route,
+// before publishing or persisting a recovery tail. Previous send tests only
+// used target-compatible values and could not detect this bypass.
+describe('pending target axis admission', () => {
+ const routes = ['cross-engine', 'remote', 'remote-same-agent', 'inherited-remote', 'return-local', 'recovery'] as const;
+ it.each(routes.flatMap(route => ['effort', 'fastMode'].map(axis => ({ route, axis }))))(
+ 'rejects stale $axis for $route without changing intent or DB', async ({ route, axis }) => {
+ const row = { agentDeviceId: route === 'inherited-remote' || route === 'remote-same-agent' || route === 'return-local' ? 'old-device' : null };
+ const bindings = axisCatalogBindings(row);
+ const providers = [{ id: 'provider', connected: true, models: { pi: [{ id: 'target', efforts: ['low'], defaultEffort: 'low', supportsFastMode: false }] } }] as unknown as ProviderView[];
+ bindings.getDesktopProviderService = () => ({ listProviders: async () => providers });
+ bindings.readUsableAgentDeviceProviders.mockResolvedValue(providers);
+ const pending = createPendingAgentSwitchRegistry();
+ const intent = { targetAgentKind: 'pi', model: 'target', providerId: 'provider', effort: 'low', fastMode: false,
+ confirmedContextWindow: 200000,
+ ...(route === 'remote' ? { targetAgentDeviceId: 'target-device' } : {}),
+ ...(route === 'remote-same-agent' ? { sameAgentSelection: true } : {}),
+ ...(route === 'return-local' ? { targetAgentDeviceId: null } : {}),
+ ...(route === 'recovery' ? { resumeFallbackRecovery: { boundaryClientId: 'boundary' } } : {}),
+ } as PendingAgentSwitchIntent;
+ pending.set('s1', intent);
+ const persist = vi.fn();
+ const changed = vi.fn();
+ const stage = compile(stageAxisAdapter, { ...bindings, agentSwitchPending: pending,
+ agentSwitchDeps: { ...bindings.agentSwitchDeps, onPendingSwitchChanged: changed,
+ selectSameAgentModel: vi.fn(async () => ({ deferred: true })) },
+ persistSessionFields: persist, projectPendingAgentSwitchIntent: (value: unknown) => value,
+ wakeSessionInputAfterCredentialSwitch: vi.fn() });
+ await expect(stage('s1', intent, axis === 'effort' ? { effort: 'xhigh' } : { fastMode: true }, vi.fn()))
+ .rejects.toThrow('INVALID_PARAMS');
+ expect(pending.get('s1')).toBe(intent);
+ expect(persist).not.toHaveBeenCalled();
+ expect(changed).not.toHaveBeenCalled();
+ const device = route === 'remote' ? 'target-device' : route === 'inherited-remote' || route === 'remote-same-agent' ? 'old-device' : null;
+ if (device) expect(bindings.readUsableAgentDeviceProviders).toHaveBeenCalledWith(device, 'pi', 'target', 'provider');
+ else expect(bindings.readUsableAgentDeviceProviders).not.toHaveBeenCalled();
+ });
+
+ it.each(['valid', 'owner-changed', 'catalog-failed'] as const)('uses the target device catalog and preserves the route: %s', async mode => {
+ const bindings = axisCatalogBindings();
+ const localRead = vi.fn(async () => []);
+ bindings.getDesktopProviderService = () => ({ listProviders: localRead });
+ if (mode === 'catalog-failed') bindings.readUsableAgentDeviceProviders.mockRejectedValue(new Error('device unavailable'));
+ const pending = createPendingAgentSwitchRegistry();
+ const intent = { targetAgentKind: 'pi', model: 'target', providerId: 'provider', effort: 'low', fastMode: false,
+ targetAgentDeviceId: 'target-device', confirmedContextWindow: 200000 } as PendingAgentSwitchIntent;
+ pending.set('s1', intent);
+ const stage = compile(stageAxisAdapter, { ...bindings, agentSwitchPending: pending,
+ projectPendingAgentSwitchIntent: (value: unknown) => value, wakeSessionInputAfterCredentialSwitch: vi.fn() });
+ const assertCurrent = () => { if (mode === 'owner-changed') throw new Error('owner changed'); };
+ const result = stage('s1', intent, { effort: 'high', fastMode: true }, assertCurrent);
+ if (mode === 'valid') {
+ await expect(result).resolves.toMatchObject({ pendingUntilSend: true });
+ expect(pending.get('s1')).toEqual({ ...intent, effort: 'high', fastMode: true });
+ } else {
+ await expect(result).rejects.toThrow(mode === 'owner-changed' ? 'owner changed' : 'device unavailable');
+ expect(pending.get('s1')).toBe(intent);
+ }
+ expect(localRead).not.toHaveBeenCalled();
+ });
+});
+
// PR #6403 round 5: earlier closure tests pre-populated the intent and skipped
// Renderer persistence. Exercise the real queue/lease and recovery boundary;
// Renderer-to-IPC persistence is covered in the existing cross-file guard suite.
@@ -115,10 +193,10 @@ describe('complete selection commit boundaries', () => {
if (fails) throw new Error('sqlite rejected');
Object.assign(row, patch);
});
- const deps = { pendingSwitches: pending, getLiveSession: () => null,
+ const deps = { pendingSwitches: pending, getLiveSession: () => null, getSessionRow: async () => row,
applyResumeFallbackAtomically: vi.fn(), setPendingHandoff: vi.fn(), onPendingSwitchChanged: vi.fn(),
log: { warn: vi.fn() } } as unknown as MakerSessionAgentSwitchHandlerDeps;
- const stageAxis = compile(stageAxisAdapter, { agentSwitchPending: pending, agentSwitchDeps: deps,
+ const stageAxis = compile(stageAxisAdapter, { ...axisCatalogBindings(row), agentSwitchPending: pending, agentSwitchDeps: deps,
persistSessionFields, projectPendingAgentSwitchIntent: (value: unknown) => value,
wakeSessionInputAfterCredentialSwitch: vi.fn() });
if (fails) {
@@ -182,10 +260,10 @@ describe('Orca model-only picker intent admission', () => {
applyPendingAgentSwitchIfIdle, isUserPendingAgentSwitchIntent, agentSwitchDeps: deps, contextOverflowRolloverHolder: null,
});
if (mode === 'cross-engine' || mode === 'relocation') {
- const stageAxis = compile(stageAxisAdapter, { agentSwitchPending: pending, agentSwitchDeps: deps,
+ const stageAxis = compile(stageAxisAdapter, { ...axisCatalogBindings(row), 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 });
+ await stageAxis('s1', pending.get('s1'), { effort: 'high' }, vi.fn());
+ await stageAxis('s1', pending.get('s1'), { fastMode: true }, vi.fn());
expect(row).toMatchObject({ status: 'archived', model: 'old', effort: 'low', fastMode: false });
}
const controller = new AbortController();
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index d604e09e27..cd15bcac26 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -22142,12 +22142,45 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
patch: Pick<PendingAgentSwitchIntent, 'effort' | 'fastMode'>,
assertCurrent: () => void,
) => {
- const updated = { ...intent, ...patch };
+ let updated = { ...intent, ...patch };
+ const row = await agentSwitchDeps.getSessionRow(sessionId);
+ if (!row) throwIpcError('PRECONDITION_FAILED', 'session is unavailable during runtime axis update');
+ const targetDeviceId = intent.targetAgentDeviceId === undefined
+ ? row.agentDeviceId : intent.targetAgentDeviceId;
+ // Local same-engine selection already validates in SET_MODEL. Its remote
+ // branch only checks route availability, so admit its axes here as well.
+ if (!intent.sameAgentSelection || targetDeviceId) {
+ const providers = targetDeviceId
+ ? await readUsableAgentDeviceProviders(targetDeviceId, intent.targetAgentKind, intent.model, intent.providerId ?? null)
+ : await getDesktopProviderService().listProviders({ allowSideEffects: false, catalog: getActiveCatalog() });
+ const providerId = intent.providerId ?? effectiveSourceIdForModel(providers, null, intent.model, intent.targetAgentKind);
+ const provider = providers.find(candidate => candidate.id === providerId);
+ const model = findCatalogModel(provider, intent.model, intent.targetAgentKind, { exact: true });
+ if (!provider?.connected || !model) {
+ throwIpcError('INVALID_PARAMS', `model "${intent.model}" is unavailable from provider "${providerId ?? 'default'}"`);
+ }
+ const axes = resolveSessionRuntimeAxes({
+ model,
+ effort: (updated.effort ?? null) as SessionRuntimeProfile['effort'],
+ fastMode: updated.fastMode ?? false,
+ effortExplicit: patch.effort !== undefined,
+ fastExplicit: patch.fastMode !== undefined,
+ allowFixedEffortPlaceholder: true,
+ });
+ if (!axes.ok) {
+ throwIpcError('INVALID_PARAMS', axes.reason === 'effort-unavailable'
+ ? `effort "${patch.effort}" is unavailable for model "${intent.model}"`
+ : `Fast is unavailable for model "${intent.model}"`);
+ }
+ updated = { ...updated, effort: axes.effort ?? undefined, fastMode: axes.fastMode };
+ }
+ // Row/catalog reads can cross an account/shared-task ownership change.
+ assertCurrent();
// Recovery is a post-commit tail: its target route already owns the DB
// fields and the next bootstrap reads them. The tail itself only repairs
// the resume boundary/handoff, so it cannot consume newly staged axes.
if (intent.resumeFallbackRecovery) {
- await persistSessionFields(sessionId, patch);
+ await persistSessionFields(sessionId, { effort: updated.effort, fastMode: updated.fastMode });
assertCurrent();
}
if (intent.sameAgentSelection) {
diff --git a/docs/dev-rules/model-catalog-runtime.md b/docs/dev-rules/model-catalog-runtime.md
index 18631247a0..56733b07c2 100644
--- a/docs/dev-rules/model-catalog-runtime.md
+++ b/docs/dev-rules/model-catalog-runtime.md
@@ -54,10 +54,11 @@ thread 配置,同时设置窗口和 90% 自动压缩预算,保留原生 5%
任务再应用;取消在恢复状态写入发出前可见时保留归档,已发出的写入不补偿回滚。
受管任务的恢复限制保持不变。暂存意图仍只在被控端
内存中保留,不新增跨进程恢复。已有用户模型意图时,无论同引擎、跨引擎或换执行电脑,
-推理强度与 Fast 都更新完整待选意图,保留目标路由和窗口确认,不改写自动意图;否则
+推理强度与 Fast 按目标模型能力校验后更新完整待选意图,保留目标路由和窗口确认,不改写自动意图;否则
只保存任务字段,不重建归档时清掉的 runtime 状态。本地与远控档位均由 Main 协调提交,
Renderer 不提前写旧路由字段;恢复尾段表示路由已提交,后续档位先保存到该目标路由,
再更新意图展示,避免仅修复交接的尾段清意图时丢掉设置。自动模型变更与已删除任务仍拒绝。
+跨引擎或远端执行的轴更新使用目标执行电脑的目录;旧窗口提交不兼容档位时拒绝,校验失败不改意图或数据库。
本机桌面、设备互联与手机共用此处理,见 `maker-ipc/register.ts` 和
`sessionRuntimeControlWiring.test.ts` 与 `orcaModelSelectionIntent.test.ts` 的归档生命周期回归。