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(bots): fence late baseline writes and final internal dispatch

Chris5af7b312236e
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
index 9817d638e0..8ecc6ef4de 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
@@ -27,7 +27,7 @@ import { BOT_TEMPLATE_PRESET_IDENTITIES } from '../../../../shared/botTemplatePr
import { normalizeWorkingDirForStorage } from '../../../../shared/workingDir';
import { createBotModelRouteReconciler } from '../../../maker-ipc/botModelRouteReconciler';
import { configureBotModelSelectionCoordinator, createBotModelSelectionCoordinator } from '../../../maker-ipc/botModelSelectionCoordinator';
-import { createScheduledModelScope, type ScheduledModelSelection } from '../../../maker-ipc/scheduledModelSelection';
+import { createScheduledModelScope, writeScheduledModelBaselineIfProfileCurrent, ScheduledModelSelectionBusyError, type ScheduledModelSelection } from '../../../maker-ipc/scheduledModelSelection';
import { acquireSendToSessionLock, withSendToSessionLock } from '../../../maker-ipc/sendToSessionLock';
import type { BotModelRoute } from '../../../../shared/botModelChain';
import type { AgentKind } from '@cindy/maker-core';
@@ -10056,9 +10056,12 @@ describe('Teammate model selection shares profile persistence and route reconcil
});
const sessionId = created.session.id as string;
const read = async () => {
- const row = h.sqlite!.prepare('SELECT agent_kind AS agentKind, model, provider_id AS providerId, effort, fast_mode AS fastMode, scheduled_model_baseline AS baseline FROM sessions WHERE id = ?')
- .get(sessionId) as ScheduledModelSelection & { baseline: string | null };
- return { profile: { ...row, fastMode: !!row.fastMode }, baseline: row.baseline };
+ const row = h.sqlite!.prepare(`SELECT s.agent_kind AS agentKind, s.model, s.provider_id AS providerId, s.effort, s.fast_mode AS fastMode,
+ s.scheduled_model_baseline AS baseline, json_array(p.id, p.current_version) AS profileRevision
+ FROM sessions s JOIN bot_session_links l ON l.session_id = s.id
+ JOIN bot_profiles p ON p.id = l.bot_id WHERE s.id = ?`)
+ .get(sessionId) as ScheduledModelSelection & { baseline: string | null; profileRevision: string };
+ return { profile: { ...row, fastMode: !!row.fastMode }, baseline: row.baseline, profileRevision: row.profileRevision };
};
const apply = async (_id: string, route: Omit<ScheduledModelSelection, 'effort'> & { effort: string | null }) => {
h.sqlite!.prepare('UPDATE sessions SET agent_kind = ?, model = ?, provider_id = ?, effort = ?, fast_mode = ? WHERE id = ?')
@@ -10082,7 +10085,10 @@ describe('Teammate model selection shares profile persistence and route reconcil
}));
const deps = { read, apply, isBusy: () => false, createId: () => 'race-scope',
prepareBaseline: (id: string) => reconcile(id, true),
- write: async (_id: string, baseline: unknown) => {
+ write: async (_id: string, baseline: Parameters<typeof writeScheduledModelBaselineIfProfileCurrent>[2] | null, revision?: string | null) => {
+ if (baseline) return writeScheduledModelBaselineIfProfileCurrent({
+ exec: async (sql, params) => h.sqlite!.prepare(sql).run(...params),
+ }, sessionId, baseline, revision ?? null);
h.sqlite!.prepare('UPDATE sessions SET scheduled_model_baseline = ? WHERE id = ?')
.run(baseline ? JSON.stringify(baseline) : null, sessionId);
},
@@ -10117,6 +10123,72 @@ describe('Teammate model selection shares profile persistence and route reconcil
expect((await read()).baseline).toBeNull();
});
+ // #6895 review, DB tier: a lane linked after the follower snapshot has no
+ // send lock in that save. The real IPC save and conditional baseline writer
+ // must reject its post-commit write, rather than resurrect A after restart.
+ it('fences a new lane baseline writer outside the model-save lock snapshot', async () => {
+ let sessionId = '';
+ const read = async () => {
+ const row = h.sqlite!.prepare(`SELECT s.agent_kind AS agentKind, s.model, s.provider_id AS providerId,
+ s.effort, s.fast_mode AS fastMode, s.scheduled_model_baseline AS baseline,
+ json_array(p.id, p.current_version) AS profileRevision
+ FROM sessions s JOIN bot_session_links l ON l.session_id = s.id
+ JOIN bot_profiles p ON p.id = l.bot_id WHERE s.id = ?`).get(sessionId) as
+ ScheduledModelSelection & { baseline: string | null; profileRevision: string };
+ return { profile: { ...row, fastMode: !!row.fastMode }, baseline: row.baseline, profileRevision: row.profileRevision };
+ };
+ const db = { exec: async (sql: string, params: unknown[]) => h.sqlite!.prepare(sql).run(...params) };
+ configureBotModelSelectionCoordinator(async (ids, operation) => {
+ const lane = await ensureBotChannelLaneSession({ botId: 'bot-1', routeKey: 'im:feishu:fixture:g:save-race', title: 'New lane' });
+ if (!lane.ok) throw new Error(lane.message);
+ sessionId = lane.sessionId;
+ expect(ids).not.toContain(sessionId);
+ let reachedWrite!: () => void;
+ const writing = new Promise<void>((resolve) => { reachedWrite = resolve; });
+ let releaseWrite!: () => void;
+ const committed = new Promise<void>((resolve) => { releaseWrite = resolve; });
+ const scope = createScheduledModelScope({ read, createId: () => 'late-lane', isBusy: () => false,
+ apply: async () => undefined,
+ write: async (id, baseline, revision) => {
+ if (!baseline) return;
+ reachedWrite();
+ await committed;
+ return writeScheduledModelBaselineIfProfileCurrent(db, id, baseline, revision ?? null);
+ },
+ });
+ const capture = scope.begin(sessionId);
+ await writing;
+ const result = await operation().finally(releaseWrite);
+ await expect(capture).rejects.toThrow(ScheduledModelSelectionBusyError);
+ return result;
+ });
+ await invoke('local-db:bots:update', { id: 'bot-1', capabilities: {
+ modelChainOverride: [{ harness: 'codex', model: 'new-saved-model', providerId: null, effort: 'medium', fastMode: false }],
+ } });
+ expect((await read()).baseline).toBeNull();
+ const bot = await invoke('local-db:bots:get', 'bot-1');
+ const apply = async (_id: string, route: ScheduledModelSelection) => {
+ h.sqlite!.prepare('UPDATE sessions SET agent_kind = ?, model = ?, provider_id = ?, effort = ?, fast_mode = ? WHERE id = ?')
+ .run(route.agentKind, route.model, route.providerId, route.effort ?? '', Number(route.fastMode), sessionId);
+ };
+ const cold = createBotModelRouteReconciler({ ownerEpoch: () => h.ownerScopeKey,
+ read: async () => ({ chain: await modelSettings.readEffectiveBotModelChain(bot.capabilities),
+ current: (await read()).profile, hasRuntimeOverride: false, scheduledModelBaseline: null }), apply,
+ });
+ expect(await cold.preview(sessionId)).toMatchObject({ model: 'new-saved-model' });
+ const deps = { read, apply, isBusy: () => false, createId: () => 'retry', prepareBaseline: cold,
+ write: async (id: string, baseline: Parameters<typeof writeScheduledModelBaselineIfProfileCurrent>[2] | null, revision?: string | null) => {
+ if (baseline) return writeScheduledModelBaselineIfProfileCurrent(db, id, baseline, revision ?? null);
+ h.sqlite!.prepare('UPDATE sessions SET scheduled_model_baseline = NULL WHERE id = ?').run(id);
+ },
+ };
+ await createScheduledModelScope(deps).begin(sessionId);
+ expect(JSON.parse((await read()).baseline!)).toMatchObject({ model: 'new-saved-model' });
+ await apply(sessionId, { agentKind: 'pi', model: 'temporary', providerId: null, effort: null, fastMode: false });
+ await createScheduledModelScope(deps).restore(sessionId);
+ expect((await read()).profile).toMatchObject({ model: 'new-saved-model' });
+ });
+
// #6895 DB regression: a crash after the profile commit but before the async
// runtime refresh must not restore the superseded choice on the next cold send.
it('commits a new model and retires its restore before runtime refresh, while unrelated edits retain it', async () => {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/scheduledModelSelection.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/scheduledModelSelection.test.ts
index 9aee8686fd..80634a92d6 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/scheduledModelSelection.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/scheduledModelSelection.test.ts
@@ -59,6 +59,20 @@ describe('one-run automation model preferences', () => {
expect(await scope.begin('task')).toBe('scope-1');
expect(prepareBaseline).toHaveBeenCalledTimes(1);
});
+ // #6895 unit regression: a lane outside the save's lock snapshot can see
+ // Profile B after preparation applied A. Do not stamp A with B's revision.
+ it('retries capture when the profile changes during route preparation', async () => {
+ const h = scopeFixture();
+ let profileRevision = 'A';
+ const write = vi.fn(h.deps.write);
+ const scope = createScheduledModelScope({ ...h.deps, write,
+ read: async () => ({ ...await h.deps.read(), profileRevision }),
+ prepareBaseline: async () => { profileRevision = 'B'; },
+ });
+ await expect(scope.begin('task')).rejects.toThrow(ScheduledModelSelectionBusyError);
+ expect(write).not.toHaveBeenCalled();
+ expect(h.state().baseline).toBeNull();
+ });
// PR #6559 + #6579 integration: the persisted scope must restore an
// Ultrafast owner after automation/restart. Existing cases used booleans;
// minimal failure is baseline JSON with fastMode='ultrafast'. Unit tier.
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.ts
index 503a73de61..70c5d131e6 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.ts
@@ -20,7 +20,7 @@ import ts from 'typescript';
import { describe, expect, it, vi } from 'vitest';
import { permissionModeOrAsk } from '@cindy/maker-shared/permission-mode';
-import { AUTO_REVIEW_SOURCE_CONTENT, AUTO_REVIEW_USER_INTENT, AUTO_REVIEW_DELEGATED_CONTINUATION, type SendOptions } from '@cindy/maker-core';
+import { AUTO_REVIEW_SOURCE_CONTENT, AUTO_REVIEW_USER_INTENT, AUTO_REVIEW_DELEGATED_CONTINUATION, TurnDispatchRejectedError, type SendOptions } from '@cindy/maker-core';
import { restoreAutoReviewUserIntent } from '../autoReviewUserIntent.js';
const registerSource = readFileSync(resolve(__dirname, '..', 'register.ts'), 'utf8').replace(
@@ -151,7 +151,7 @@ function botTaskDispatchHarness(
limit: async () => [],
};
const stubs: Record<string, unknown> = {
- assertTaskActionCurrent, hasTaskActionAuthorization,
+ assertTaskActionCurrent, hasTaskActionAuthorization, TurnDispatchRejectedError,
AUTO_REVIEW_SOURCE_CONTENT, AUTO_REVIEW_USER_INTENT, AUTO_REVIEW_DELEGATED_CONTINUATION,
restoreAutoReviewUserIntent, readAutoReviewHistory,
maker: {
@@ -219,11 +219,15 @@ function botTaskDispatchHarness(
session: { id: string },
_message: string,
_clientId: string,
- opts: SendOptions & { onAccepted?: () => Promise<void> },
+ opts: SendOptions & { onAccepted?: () => Promise<void>; onDispatching?: () => void },
) => {
- sentTo.push({ sessionId: session.id, planMode: opts.planMode });
sendOptions.push(opts);
await opts.onAccepted?.();
+ try { opts.onDispatching?.(); } catch (error) {
+ if (error instanceof TurnDispatchRejectedError) return { accepted: false, reason: 'provider-rejected-before-dispatch' };
+ throw error;
+ }
+ sentTo.push({ sessionId: session.id, planMode: opts.planMode });
return { accepted: true };
},
assertDesktopSendDispatched: noop,
@@ -293,6 +297,27 @@ describe('companion internal delivery after automation', () => {
expect(enqueue).not.toHaveBeenCalled();
});
+ // #6895 review: the post-restore check precedes asynchronous bootstrap and
+ // acceptance. Guard tier: demote at message persistence, then execute the real
+ // dispatch callback and prove neither live nor resumed delivery reaches send.
+ it.each(['live', 'resumed'] as const)('rejects %s delivery demoted immediately before dispatch', async (path) => {
+ let shadowed = false;
+ const dbChain = { from: () => dbChain, where: () => dbChain,
+ limit: async () => [{ role: 'canonical', botId: 'companion' }] };
+ const h = botTaskDispatchHarness({ child: { permissionMode: 'auto', planModeEnabled: false } },
+ path === 'live' ? { child: { id: 'child', agentKind: 'pi', isTurnRunning: () => false, getStatus: () => 'active' } } : {}, {
+ getDbClient: () => ({ drizzle: { select: () => dbChain } }),
+ isShadowedCompanionCanonical, isCompanionShadowed: () => shadowed,
+ createDbMessage: async () => { shadowed = true; },
+ });
+ expect(await h.dispatchBotSessionMessage({ targetSessionId: 'child', message: 'Late cloud input' }))
+ .toMatchObject({ ok: false, errorCode: 'AGENT_NOT_READY', message: 'shadowed' });
+ expect(shadowed).toBe(true);
+ expect(h.sentTo).toEqual([]);
+ expect(h.sendOptions).toHaveLength(1);
+ expect(h.bootstrapped).toHaveLength(path === 'resumed' ? 1 : 0);
+ });
+
it.each(['live', 'resumed'] as const)('restores before %s dispatch reads its model', async (path) => {
const saved = { agentKind: 'pi' as const, model: 'saved-model', providerId: 'fixture-provider', effort: null, fastMode: false };
let current = { ...saved, agentKind: 'codex' as 'codex' | 'pi', model: 'temporary-model' };
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index bf547119ca..8c26413b1c 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -152,7 +152,7 @@ import {
} from '@cindy/maker-core/pi-subagent-runs';
import {
PI_CACHE_RECOVERY_EXPECTATION, AUTO_REVIEW_SOURCE_CONTENT, AUTO_REVIEW_USER_INTENT,
- INHERITED_CAPABILITY_SELECTION, MAIN_OWNED_SEND_CONTEXT,
+ INHERITED_CAPABILITY_SELECTION, MAIN_OWNED_SEND_CONTEXT, TurnDispatchRejectedError,
} from '@cindy/maker-core';
import { AUTO_REVIEW_DELEGATED_CONTINUATION, readAutoReviewUserText, restoreAutoReviewSteerIntent, restoreAutoReviewUserIntent } from './autoReviewUserIntent.js';
import type {
@@ -197,7 +197,7 @@ import {
readInputDeliveryClientIds,
} from '@cindy/device-link';
import { and, asc, desc, eq, gte, inArray, isNull, like, lt, or, sql } from 'drizzle-orm';
-import { applyScheduledModelSelection, createScheduledModelScope, ScheduledModelSelectionBusyError, type ScheduledModelSelection, type ScheduledModelSelectionLease } from './scheduledModelSelection';
+import { applyScheduledModelSelection, createScheduledModelScope, writeScheduledModelBaselineIfProfileCurrent, ScheduledModelSelectionBusyError, type ScheduledModelSelection, type ScheduledModelSelectionLease } from './scheduledModelSelection';
import { parseScheduledModelBaseline } from '../../shared/scheduledModelBaseline';
import { recordTurnModelChange, type TurnModelIdentity } from './turnModelChange';
import { app, BrowserWindow, dialog, ipcMain, shell, type IpcMainInvokeEvent } from 'electron';
@@ -11088,23 +11088,33 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const [row] = await getDbClient().drizzle.select({
agentKind: sessions.agentKind, model: sessions.model, providerId: sessions.providerId,
effort: sessions.effort, fastMode: sessions.fastMode, baseline: sessions.scheduledModelBaseline,
- status: sessions.status,
- }).from(sessions).where(eq(sessions.id, sessionId)).limit(1);
- return row?.status === 'active' ? { baseline: row.baseline, profile: {
+ status: sessions.status, botId: botProfiles.id, profileVersion: botProfiles.currentVersion,
+ }).from(sessions)
+ .leftJoin(botSessionLinks, and(eq(botSessionLinks.sessionId, sessions.id),
+ isNull(botSessionLinks.archivedAt), inArray(botSessionLinks.role, ['canonical', 'group', 'channel', 'thread'])))
+ .leftJoin(botProfiles, eq(botProfiles.id, botSessionLinks.botId))
+ .where(eq(sessions.id, sessionId)).limit(1);
+ return row?.status === 'active' ? { baseline: row.baseline,
+ profileRevision: row.botId ? JSON.stringify([row.botId, row.profileVersion]) : null, profile: {
agentKind: dbToMakerAgentKind(row.agentKind), model: row.model, providerId: row.providerId,
effort: row.effort, fastMode: row.fastMode,
} } : null;
},
- write: async (sessionId, baseline) => {
+ write: async (sessionId, baseline, profileRevision) => {
+ if (baseline) {
+ const written = await writeScheduledModelBaselineIfProfileCurrent(getDbClient(), sessionId, baseline, profileRevision ?? null);
+ if (written) await broadcastSessionRuntimeProjection(sessionId);
+ return written;
+ }
const owner = captureSessionRuntimeControlOwnerEpoch();
const db = getDbClient().drizzle;
- const [row] = baseline ? [] : await db.select({ baseline: sessions.scheduledModelBaseline })
+ const [row] = await db.select({ baseline: sessions.scheduledModelBaseline })
.from(sessions).where(eq(sessions.id, sessionId)).limit(1);
const saved = parseScheduledModelBaseline(row?.baseline);
if (!sessionRuntimeControlOwnerEpochMatches(owner)) throw new Error('Account changed during scheduled model selection');
await db.update(sessions)
.set({
- scheduledModelBaseline: baseline ? JSON.stringify(baseline) : null,
+ scheduledModelBaseline: null,
...(saved ? {
agentKind: makerToDbAgentKind(saved.agentKind), model: saved.model,
providerId: saved.providerId, effort: saved.effort ?? undefined, fastMode: saved.fastMode,
@@ -11600,15 +11610,28 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// Check before route/capability reconciliation, then again after waiting for
// the send lock: a rejected old primary must not bootstrap or consume a restore.
+ let dispatchCompanionLink: { role?: string | null; botId?: string | null } | undefined;
const rejectShadowedCompanion = async (sessionId: string) => {
const [link] = await getDbClient().drizzle
.select({ role: botSessionLinks.role, botId: botSessionLinks.botId })
.from(botSessionLinks).where(eq(botSessionLinks.sessionId, sessionId)).limit(1);
+ dispatchCompanionLink = link;
return isShadowedCompanionCanonical(link, isCompanionShadowed)
? { ok: false as const, errorCode: 'AGENT_NOT_READY' as const, message: SHADOWED_COMPANION_INPUT_MESSAGE }
: null;
};
+ let dispatchRejectedForDemotion = false;
+ const onInternalDispatching = () => {
+ // Session invokes this synchronously immediately before provider send,
+ // after bootstrap, authorization and message persistence have all awaited.
+ if (isShadowedCompanionCanonical(dispatchCompanionLink, isCompanionShadowed)) {
+ dispatchRejectedForDemotion = true;
+ throw new TurnDispatchRejectedError(SHADOWED_COMPANION_INPUT_MESSAGE);
+ }
+ dispatchAgentIslandUserPrompt(targetSessionId!);
+ };
+
if (targetSessionId) {
try {
await assertReviewExternalInputAllowed(targetSessionId);
@@ -12151,7 +12174,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
} : {}),
planMode: false,
onAccepted: persistUserMessage,
- onDispatching: () => dispatchAgentIslandUserPrompt(targetSessionId),
+ onDispatching: onInternalDispatching,
}, directSource);
if (userPromptPreviewStarted) {
if (sendResult.accepted) {
@@ -12164,6 +12187,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
);
}
}
+ if (dispatchRejectedForDemotion) {
+ return { ok: false as const, errorCode: 'AGENT_NOT_READY' as const, message: SHADOWED_COMPANION_INPUT_MESSAGE };
+ }
assertDesktopSendDispatched(sendResult, 'send_to_session live');
return {
ok: true as const,
@@ -12281,7 +12307,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
} : {}),
planMode: false,
onAccepted: persistUserMessage,
- onDispatching: () => dispatchAgentIslandUserPrompt(targetSessionId),
+ onDispatching: onInternalDispatching,
}, directSource);
if (userPromptPreviewStarted) {
if (sendResult.accepted) {
@@ -12294,6 +12320,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
);
}
}
+ if (dispatchRejectedForDemotion) {
+ return { ok: false as const, errorCode: 'AGENT_NOT_READY' as const, message: SHADOWED_COMPANION_INPUT_MESSAGE };
+ }
assertDesktopSendDispatched(sendResult, 'send_to_session resumed');
return {
ok: true as const,
diff --git a/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts b/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts
index de671c48e4..a72d971ed1 100644
--- a/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts
+++ b/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts
@@ -25,8 +25,9 @@ export function createScheduledModelScope(deps: {
effort: ScheduledModelSelection['effort'] | '';
};
baseline: string | null;
+ profileRevision?: string | null;
} | null>;
- write: (sessionId: string, baseline: ScheduledModelBaseline | null) => Promise<void>;
+ write: (sessionId: string, baseline: ScheduledModelBaseline | null, profileRevision?: string | null) => Promise<void | boolean>;
isBusy: (sessionId: string) => boolean;
apply: (sessionId: string, profile: ScheduledModelSelection) => Promise<void>;
createId: () => string;
@@ -44,6 +45,7 @@ export function createScheduledModelScope(deps: {
if (!row) return undefined;
const existing = parseScheduledModelBaseline(row.baseline);
if (existing) return existing.scopeId;
+ const profileRevision = row.profileRevision;
// Settings may have committed while their asynchronous runtime refresh is
// still queued. Align the owner under this same send lease before capture.
if (deps.prepareBaseline) {
@@ -53,8 +55,14 @@ export function createScheduledModelScope(deps: {
assertOwner(owner);
if (!row) return undefined;
}
+ if (row.profileRevision !== profileRevision) {
+ throw new ScheduledModelSelectionBusyError('Companion profile changed during baseline preparation');
+ }
const scopeId = deps.createId();
- await deps.write(sessionId, { ...row.profile, effort: row.profile.effort || null, scopeId });
+ const written = await deps.write(sessionId, { ...row.profile, effort: row.profile.effort || null, scopeId }, profileRevision);
+ if (written === false) {
+ throw new ScheduledModelSelectionBusyError('Companion profile changed during baseline capture');
+ }
return scopeId;
},
async restore(sessionId: string, expectedScopeId?: string): Promise<void> {
@@ -72,6 +80,26 @@ export function createScheduledModelScope(deps: {
};
}
+/** Fence even lanes linked after the settings save took its send-lock snapshot.
+ * The revision is read with the route; checking and writing are one DB statement.
+ * Ordinary sessions use null, so acquiring a companion link also invalidates capture.
+ */
+export async function writeScheduledModelBaselineIfProfileCurrent(
+ db: { exec: (sql: string, params: unknown[]) => Promise<{ changes: number }> },
+ sessionId: string,
+ baseline: ScheduledModelBaseline,
+ profileRevision: string | null,
+): Promise<boolean> {
+ const result = await db.exec(`UPDATE sessions SET scheduled_model_baseline = ?
+ WHERE id = ? AND status = 'active'
+ AND (SELECT json_array(p.id, p.current_version)
+ FROM bot_session_links l JOIN bot_profiles p ON p.id = l.bot_id
+ WHERE l.session_id = sessions.id AND l.archived_at IS NULL
+ AND l.role IN ('canonical', 'group', 'channel', 'thread') LIMIT 1) IS ?`,
+ [JSON.stringify(baseline), sessionId, profileRevision]);
+ return result.changes === 1;
+}
+
export class ScheduledModelSelectionBusyError extends Error {}
interface ScheduledModelTarget {
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index eaa870a913..b496aee88b 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -362,7 +362,7 @@ harness + provider + model + effort + fastMode
- 同一轮最多按生效候选链各尝试一次;不得循环。用户显式配置的链不得追加目录候选。
- 同 harness 可在安全边界切模型;跨 harness 必须走既有 agent-switch / 交接重建事务。
- 伙伴设置中的显式模型保存立即同步当前主任务的运行选择;空闲时在既有安全边界完成切换,运行中先记录最新选择,在回复、工具与审批结束后的安全边界接替,不要求用户再发一条消息才能登记。连续改选以最后一次为准,选回当前路由应取消不同的待切换路由。
-- 自动化指定的临时模型在本轮发送中不被伙伴默认模型对齐覆盖,包括跟随全局默认的伙伴。主人随后保存新的伙伴模型选择时,在发送锁内以同一数据库事务清除活跃主任务及群/IM 专线的旧恢复偏好,并同步标记模型对齐失效;新自动化记录恢复选择前在同一发送锁内对齐已保存模型,避免异步运行态刷新尚未执行时重新写回旧选择。设置已保存但运行态刷新前退出也不会复活旧选择;即使新选择恰好等于临时运行模型,下一次聊天也不得恢复到旧选择。普通内部投递先拒绝已降级的伙伴副本,再在发送边界恢复原选择;能力设置预览使用下一轮普通聊天的选择,不因预览消费恢复记录。
+- 自动化指定的临时模型在本轮发送中不被伙伴默认模型对齐覆盖,包括跟随全局默认的伙伴。主人随后保存新的伙伴模型选择时,在发送锁内以同一数据库事务清除活跃主任务及群/IM 专线的旧恢复偏好,并同步标记模型对齐失效;新自动化记录恢复选择前在同一发送锁内对齐已保存模型,避免异步运行态刷新尚未执行时重新写回旧选择。恢复记录写入还须原子校验读取路由时的伙伴 Profile 版本,覆盖保存期间新建、尚未进入发送锁快照的专线;版本变化时重新准备,不能写回旧选择。设置已保存但运行态刷新前退出也不会复活旧选择;即使新选择恰好等于临时运行模型,下一次聊天也不得恢复到旧选择。普通内部投递先拒绝已降级的伙伴副本,再在发送边界恢复原选择,并在所有异步准备结束、真正派发给 Agent 前同步重查降级状态;能力设置预览使用下一轮普通聊天的选择,不因预览消费恢复记录。
- 模型配置只保留统一选择器入口,备用链仍在原组件内折叠;思考深度、Fast 与 Harness 不拆成独立设置页。缩窗交接复用已经核实目标窗口的延迟选择处理,完整记录与主任务身份保留,不绕过原生副作用重放限制。
- fallback 只改变当前任务的有效路由,不暗改 Profile 顺序。下一次确定性重建仍从首选开始。
- 存量单模型配置归一成一项候选链,不能在升级时改变用户已有选择。