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(model-default): 进行中任务的 Auto 换了供应商后,下一条消息前自动切过去

fmfsaisaib6485a22fcb7
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/cindyAutoRouteFollow.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/cindyAutoRouteFollow.test.ts
new file mode 100644
index 0000000000..ad4b4f4e49
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/cindyAutoRouteFollow.test.ts
@@ -0,0 +1,150 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { CatalogModel, ProviderSource, ProviderView } from '@cindy/model-providers';
+
+import {
+ followMovedCindyAutoRoutes,
+ movedCindyAutoProviderId,
+ type CindyAutoRoute,
+ type CindyAutoRouteFollowDeps,
+} from '../cindyAutoRouteFollow.js';
+
+const AUTO = 'auto/group-1';
+
+function model(id: string): CatalogModel {
+ return { id, name: id, contextWindow: 200_000, efforts: [], defaultEffort: null };
+}
+
+function provider(id: string, source: ProviderSource, modelIds: string[]): ProviderView {
+ return {
+ id,
+ name: id,
+ source,
+ agents: ['pi'],
+ auth: { method: source === 'user' ? 'apiKey' : 'managed' },
+ access: source === 'user' ? { kind: 'api' } : { kind: 'managed' },
+ routing: { pi: { upstream: `https://${id}.test`, authStrategy: 'api-key-header' } },
+ models: { pi: modelIds.map(model) },
+ connected: true,
+ };
+}
+
+const route = (patch: Partial<CindyAutoRoute> = {}): CindyAutoRoute => ({
+ agentKind: 'pi',
+ model: AUTO,
+ providerId: 'org-pool',
+ effort: 'high',
+ fastMode: false,
+ ...patch,
+});
+
+/** 管理员把 Auto 的目标从号池模型切到平台模型。 */
+const movedToPlatform = [
+ provider('xd', 'builtin', ['auto', AUTO]),
+ provider('org-pool', 'organization', ['pool-model']),
+];
+
+describe('movedCindyAutoProviderId', () => {
+ it('Auto 换了 Cindy 来源时给出新来源,引擎与模型不在这里改', () => {
+ expect(movedCindyAutoProviderId(movedToPlatform, route())).toBe('xd');
+ const movedToPool = [provider('xd', 'builtin', ['auto']), provider('org-pool', 'organization', [AUTO])];
+ expect(movedCindyAutoProviderId(movedToPool, route({ providerId: 'xd' }))).toBe('org-pool');
+ });
+
+ it('Pi 的默认来源(providerId=null)就是 Cindy AI,Auto 挪到号池同样跟随', () => {
+ const movedToPool = [provider('xd', 'builtin', ['auto']), provider('org-pool', 'organization', [AUTO])];
+ expect(movedCindyAutoProviderId(movedToPool, route({ providerId: null }))).toBe('org-pool');
+ // 其它引擎的默认来源不一定是 Cindy AI,不推断。
+ expect(movedCindyAutoProviderId(movedToPool, route({ providerId: null, agentKind: 'codex' }))).toBeNull();
+ });
+
+ it('来源没变、普通模型、用户自己接的供应商都不动', () => {
+ expect(movedCindyAutoProviderId(movedToPlatform, route({ providerId: 'xd' }))).toBeNull();
+ expect(movedCindyAutoProviderId(movedToPlatform, route({ model: 'pool-model' }))).toBeNull();
+ const userOwned = [provider('custom', 'user', ['other']), provider('xd', 'builtin', [AUTO])];
+ expect(movedCindyAutoProviderId(userOwned, route({ providerId: 'custom' }))).toBeNull();
+ });
+});
+
+describe('followMovedCindyAutoRoutes', () => {
+ function deps(overrides: Partial<CindyAutoRouteFollowDeps> = {}) {
+ const stage = vi.fn(async () => {});
+ const withSessionLock = vi.fn(async (_sessionId: string, run: () => Promise<void>) => run());
+ const base: CindyAutoRouteFollowDeps = {
+ listCandidates: async () => [
+ { sessionId: 'moved', ...route() },
+ { sessionId: 'unchanged', ...route({ providerId: 'xd' }) },
+ { sessionId: 'plain', ...route({ model: 'pool-model' }) },
+ ],
+ listProviders: async () => movedToPlatform,
+ withSessionLock,
+ readRoute: async (sessionId) =>
+ sessionId === 'moved' ? route({ effort: 'medium', fastMode: true }) : route({ providerId: 'xd' }),
+ stage,
+ assertCurrent: () => {},
+ };
+ return { stage, withSessionLock, deps: { ...base, ...overrides } };
+ }
+
+ it('只为 Auto 被挪走的任务登记下一条消息前的切换:只换供应商,保留引擎、模型与档位', async () => {
+ const { stage, withSessionLock, deps: input } = deps();
+ await expect(followMovedCindyAutoRoutes(input)).resolves.toBe(1);
+ expect(withSessionLock).toHaveBeenCalledTimes(1);
+ expect(stage).toHaveBeenCalledWith('moved', {
+ agentKind: 'pi', model: AUTO, providerId: 'xd', effort: 'medium', fastMode: true,
+ });
+ });
+
+ it('加锁后重读:已有登记的切换或运行时改道(readRoute 返回 null)时不覆盖', async () => {
+ const { stage, deps: input } = deps({ readRoute: async () => null });
+ await expect(followMovedCindyAutoRoutes(input)).resolves.toBe(0);
+ expect(stage).not.toHaveBeenCalled();
+ });
+
+ it('没有候选任务时不读供应商目录', async () => {
+ const listProviders = vi.fn(async () => movedToPlatform);
+ const { deps: input } = deps({ listCandidates: async () => [], listProviders });
+ await expect(followMovedCindyAutoRoutes(input)).resolves.toBe(0);
+ expect(listProviders).not.toHaveBeenCalled();
+ });
+
+ it('单个任务登记失败只记日志,其余任务继续', async () => {
+ const logger = { info: vi.fn() };
+ const stage = vi.fn(async (sessionId: string) => {
+ if (sessionId === 'first') throw new Error('window check failed');
+ });
+ const { deps: input } = deps({
+ listCandidates: async () => [
+ { sessionId: 'first', ...route() },
+ { sessionId: 'second', ...route() },
+ ],
+ readRoute: async () => route(),
+ stage,
+ logger,
+ });
+ await expect(followMovedCindyAutoRoutes(input)).resolves.toBe(1);
+ expect(stage).toHaveBeenCalledTimes(2);
+ expect(logger.info).toHaveBeenCalledWith(
+ 'Cindy Auto provider follow failed; task keeps its route',
+ expect.objectContaining({ sessionId: 'first' }),
+ );
+ });
+
+ it('账号切换后整批停止,不再改动下一个账号的任务', async () => {
+ let current = true;
+ const stage = vi.fn(async () => { current = false; });
+ const { deps: input } = deps({
+ listCandidates: async () => [
+ { sessionId: 'first', ...route() },
+ { sessionId: 'second', ...route() },
+ ],
+ readRoute: async () => route(),
+ stage,
+ assertCurrent: () => {
+ if (!current) throw new Error('owner changed');
+ },
+ });
+ await expect(followMovedCindyAutoRoutes(input)).rejects.toThrow('owner changed');
+ expect(stage).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/cindyAutoRouteFollow.ts b/apps/desktop/src/main/maker-ipc/cindyAutoRouteFollow.ts
new file mode 100644
index 0000000000..80e68fa95f
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/cindyAutoRouteFollow.ts
@@ -0,0 +1,88 @@
+import {
+ effectiveSourceIdForModel,
+ isCindyAutoModelId,
+ type AgentKind,
+ type ProviderView,
+} from '@cindy/model-providers';
+
+/**
+ * 进行中任务跟随服务端挪动的 Auto。
+ *
+ * 模型组 Auto(`auto/<组ID>`)挂在 Cindy AI 还是企业号池供应商下由服务端决定,管理员在
+ * 平台模型与号池模型之间切换目标后,同一个模型 ID 会换到另一家供应商。目录刷新后,把仍记着
+ * 旧来源的进行中任务登记为「下一条消息前切换」:引擎与模型 ID 不变,只换供应商(随之换 Key),
+ * 沿用系统按配置发起的切换流程。不抢占运行中的轮次,不覆盖已登记的切换或运行时改道。
+ */
+
+export interface CindyAutoRoute {
+ agentKind: AgentKind;
+ model: string;
+ providerId: string | null;
+ effort: string | null;
+ fastMode: boolean;
+}
+
+/** Pi 的 providerId=null 就是 Cindy AI 网关;其它引擎的 null 不一定落在 Cindy AI,不推断。 */
+function rememberedProviderId(route: CindyAutoRoute): string | null {
+ return route.providerId ?? (route.agentKind === 'pi' ? 'xd' : null);
+}
+
+/** 该路由的 Auto 已被服务端挪到另一家 Cindy 来源时返回新来源,否则 null。 */
+export function movedCindyAutoProviderId(
+ providers: readonly ProviderView[],
+ route: CindyAutoRoute,
+): string | null {
+ if (!isCindyAutoModelId(route.model)) return null;
+ const remembered = rememberedProviderId(route);
+ if (!remembered) return null;
+ const effective = effectiveSourceIdForModel([...providers], remembered, route.model, route.agentKind);
+ return effective && effective !== remembered ? effective : null;
+}
+
+export interface CindyAutoRouteFollowDeps {
+ /** 本机进行中、正在用 Auto 的任务(目录刷新时的粗筛,加锁后会重读)。 */
+ listCandidates(): Promise<readonly ({ sessionId: string } & CindyAutoRoute)[]>;
+ listProviders(): Promise<readonly ProviderView[]>;
+ withSessionLock(sessionId: string, run: () => Promise<void>): Promise<void>;
+ /** 加锁后重读任务当前实际路由;已有登记的切换或运行时改道时返回 null,不覆盖。 */
+ readRoute(sessionId: string): Promise<CindyAutoRoute | null>;
+ /** 登记下一条消息前的切换(调用方已持有该任务的 send 锁)。 */
+ stage(sessionId: string, route: CindyAutoRoute): Promise<void>;
+ assertCurrent(): void;
+ logger?: { info(message: string, meta?: Record<string, unknown>): void };
+}
+
+/** 返回本次登记了切换的任务数;单个任务失败只记日志,不影响其余任务。 */
+export async function followMovedCindyAutoRoutes(deps: CindyAutoRouteFollowDeps): Promise<number> {
+ const candidates = await deps.listCandidates();
+ if (candidates.length === 0) return 0;
+ const providers = await deps.listProviders();
+ deps.assertCurrent();
+ let staged = 0;
+ for (const candidate of candidates) {
+ if (!movedCindyAutoProviderId(providers, candidate)) continue;
+ try {
+ await deps.withSessionLock(candidate.sessionId, async () => {
+ deps.assertCurrent();
+ const route = await deps.readRoute(candidate.sessionId);
+ const providerId = route ? movedCindyAutoProviderId(providers, route) : null;
+ if (!route || !providerId) return;
+ await deps.stage(candidate.sessionId, { ...route, providerId });
+ staged += 1;
+ deps.logger?.info('Cindy Auto moved provider; staged switch for next message', {
+ sessionId: candidate.sessionId,
+ model: route.model,
+ from: route.providerId,
+ to: providerId,
+ });
+ });
+ } catch (error) {
+ deps.assertCurrent();
+ deps.logger?.info('Cindy Auto provider follow failed; task keeps its route', {
+ sessionId: candidate.sessionId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ return staged;
+}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 11963fb6ba..18f2594662 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -172,7 +172,7 @@ import {
DL_SESSION_REFERENCE_CAPABILITY_CHANNEL,
readInputDeliveryClientIds,
} from '@cindy/device-link';
-import { and, asc, desc, eq, gte, inArray, isNull, lt, sql } from 'drizzle-orm';
+import { and, asc, desc, eq, gte, inArray, isNull, like, lt, or, sql } from 'drizzle-orm';
import { applyScheduledModelSelection, ScheduledModelSelectionBusyError, type ScheduledModelSelection, type ScheduledModelSelectionLease } from './scheduledModelSelection';
import { app, BrowserWindow, dialog, ipcMain, shell, type IpcMainInvokeEvent } from 'electron';
import {
@@ -508,6 +508,7 @@ import {
} from '../localDb/schema.js';
import { nextBotModelRoute, normalizeBotModelChain, type BotModelRoute } from '../../shared/botModelChain.js';
import { createBotModelRouteReconciler } from './botModelRouteReconciler.js';
+import { followMovedCindyAutoRoutes } from './cindyAutoRouteFollow.js';
import { readEffectiveBotModelChain, readEffectiveBotModelSelection } from '../maker-host/bot-model-chain-settings-store.js';
import {
isOrcaWorkerPermissionMode,
@@ -5896,9 +5897,18 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
async () => { throw new Error('Pi model settings refresh is not ready'); };
let applyPiPendingSelection: NonNullable<PendingCredentialSwitchDeps['applyPiPending']> =
async () => { throw new Error('Pi pending model switch is not ready'); };
+ let followMovedCindyAutoRoutesNow: () => Promise<void> = async () => {};
const refreshContextSettings = (targets?: readonly { agent: AgentKind; providerId: string; modelId: string }[]) => {
const owner = getActiveAppSession();
- const next = contextRefresh.then(() => refreshActiveModelContextSettings({
+ const next = contextRefresh.then(async () => {
+ // 目录刷新先登记被服务端挪走的 Auto:之后的上下文刷新会跳过已登记切换的任务,
+ // 不再按旧来源重载一个已不提供该模型的连接。
+ if (!targets) {
+ await followMovedCindyAutoRoutesNow().catch((error) => log.warn('Cindy Auto provider follow failed', {
+ error: error instanceof Error ? error.message : String(error),
+ }));
+ }
+ }).then(() => refreshActiveModelContextSettings({
targets, inferProviderId: (model, agent) => resolveDesktopModelContextProviderId(getActiveCatalog(), agent, null, model),
withSessionLock: withSendToSessionLock,
applyPiRefresh: applyPiModelSettingsRefresh,
@@ -14855,6 +14865,53 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
{ source: 'user', deferWhileRunning: true, sessionLockHeld: true, configStaged: true }));
}
};
+ followMovedCindyAutoRoutesNow = async () => {
+ const owner = getActiveAppSession();
+ await followMovedCindyAutoRoutes({
+ // 远程主机 / 另一台电脑上运行的任务,路由由那一端的目录决定,不在本机改道。
+ listCandidates: async () => (await getDbClient().drizzle.select({
+ sessionId: sessions.id,
+ agentKind: sessions.agentKind,
+ model: sessions.model,
+ providerId: sessions.providerId,
+ effort: sessions.effort,
+ fastMode: sessions.fastMode,
+ }).from(sessions).where(and(
+ eq(sessions.status, 'active'),
+ or(eq(sessions.model, 'auto'), like(sessions.model, 'auto/%')),
+ isNull(sessions.remoteHostId),
+ isNull(sessions.agentDeviceId),
+ ))).map((row) => ({
+ sessionId: row.sessionId,
+ agentKind: dbToMakerAgentKind(row.agentKind),
+ model: row.model,
+ providerId: row.providerId?.trim() || null,
+ effort: row.effort ?? null,
+ fastMode: row.fastMode === true,
+ })),
+ listProviders: () => getDesktopProviderService().listProviders({
+ allowSideEffects: false,
+ catalog: getActiveCatalog(),
+ }),
+ withSessionLock: withSendToSessionLock,
+ readRoute: async (sessionId) => {
+ // 用户或系统已登记的切换、运行时改道都是更晚的决定,不覆盖。
+ if (agentSwitchPending.get(sessionId)) return null;
+ const credentialSwitch = getPendingCredentialSwitchTarget(sessionId);
+ if (credentialSwitch && credentialSwitch.selectionSource !== 'agent') return null;
+ const profiles = await readSessionRuntimeProfiles(sessionId);
+ if (!profiles || profiles.pendingMutation || profiles.control.effectiveOverride) return null;
+ return profiles.effective;
+ },
+ stage: (sessionId, route) => stageSessionRouteSelection(sessionId, route, route.agentKind),
+ assertCurrent: () => {
+ if (getActiveAppSession().generation !== owner.generation) {
+ throw new Error('Account changed during Cindy Auto provider follow');
+ }
+ },
+ logger: log,
+ });
+ };
const isSessionIdleForRouteApply = (sessionId: string): boolean => {
const live = maker.getSession(sessionId) as WiredSession | undefined;
return !live?.isTurnRunning() && (live?.listBackgroundTasks().length ?? 0) === 0
diff --git a/docs/dev-rules/model-catalog-maintenance.md b/docs/dev-rules/model-catalog-maintenance.md
index f24b159623..180b023f6e 100644
--- a/docs/dev-rules/model-catalog-maintenance.md
+++ b/docs/dev-rules/model-catalog-maintenance.md
@@ -146,6 +146,9 @@ Auto 只按模型 ID 认(`isCindyAutoModelId`):服务端可以把同一个
之间挪动。记住的来源是这两类之一且已不再提供它时,`effectiveSourceIdForModel` 改用当前提供它
的那一家(同样限于这两类),新建任务提交与手机端 `resolveRecentModelAndProvider` 复用同一规则;
记住的来源仍列着它(只是断连或停用)、或是用户自己接的供应商时不改道。
+目录刷新后,仍记着旧来源的进行中任务登记一次「下一条消息前切换」:引擎与模型 ID 不变,只换
+供应商与 Key(`apps/desktop/src/main/maker-ipc/cindyAutoRouteFollow.ts`);已有登记的切换或
+运行时改道不覆盖,远程主机与另一台电脑上运行的任务不在本机改道。请求被拒后刷新目录重试不在客户端处理。
设置页管理列表组内与选择器同序:组内每项都带 `sortOrder` 时按它排;只要有一项缺失,退回
按系列名 A–Z、同系列版本号降序,避免局部权重把新型号压到旧策展位置之后。