Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): fence automation scopes against permanent model saves
ylliuuu66fcacda041d56
diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.tsindex 12822688e6..fd5d2d3ef4 100644--- a/apps/desktop/src/main/localDb/client/tx/types.ts+++ b/apps/desktop/src/main/localDb/client/tx/types.ts@@ -25,6 +25,7 @@ export type DbTxName =| 'orca.archiveWorkersByTeam'| 'orca.reconcileInactiveTeamWorkersForLead'| 'sessions.renameTitles'+ | 'sessions.createScheduledModelBaseline'| 'sessions.setStatus'| 'sessions.setTerminalStatus'| 'recentWorkdirs.mergeWindowsIdentity'@@ -1402,6 +1403,7 @@ export type DbTxArgsByName = {'orca.archiveWorkersByTeam': OrcaArchiveWorkersByTeamArgs;'orca.reconcileInactiveTeamWorkersForLead': OrcaReconcileInactiveTeamWorkersForLeadArgs;'sessions.renameTitles': SessionsRenameTitlesArgs;+ 'sessions.createScheduledModelBaseline': { sessionId: string; baseline: string; expectedBaseline: string | null };'sessions.setStatus': SessionsSetStatusArgs;'sessions.setTerminalStatus': SessionsSetTerminalStatusArgs;'recentWorkdirs.mergeWindowsIdentity': RecentWorkdirsMergeWindowsIdentityArgs;@@ -1497,6 +1499,7 @@ export type DbTxResultByName = {'orca.archiveWorkersByTeam': string[];'orca.reconcileInactiveTeamWorkersForLead': string[];'sessions.renameTitles': SessionsRenameTitleResult[];+ 'sessions.createScheduledModelBaseline': boolean;'sessions.setStatus': SessionsSetStatusResultItem[];'sessions.setTerminalStatus': SessionsSetTerminalStatusResult;'recentWorkdirs.mergeWindowsIdentity': undefined;diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/botTx.test.ts b/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/botTx.test.tsindex 1a09d70e92..c1461be8dc 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/botTx.test.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/botTx.test.ts@@ -107,12 +107,18 @@ describe('Bot named worker transactions', () => {},onSelectionAccepted: async () => { writeBaseline(null); },});- const scope = createScheduledModelScope({+ const scopeDeps: Parameters<typeof createScheduledModelScope>[0] = {read: async () => ({ profile: current, baseline: readBaseline() }),- write: async (_id, baseline) => writeBaseline(baseline ? JSON.stringify(baseline) : null),+ write: async (sessionId, baseline, expectedBaseline) => {+ if (baseline) return tx(db, { name: 'sessions.createScheduledModelBaseline', args: {+ sessionId, baseline: JSON.stringify(baseline), expectedBaseline,+ } }) as boolean;+ writeBaseline(null);+ },apply: async (_id, route) => { current = route; }, isBusy: () => false, createId: () => 'unused',- });- return { original, readBaseline, pause, save, reconcile, scope, current: () => current,+ };+ const scope = createScheduledModelScope(scopeDeps);+ return { original, readBaseline, pause, save, reconcile, scope, scopeDeps, writeBaseline, current: () => current,changeOwner: () => { owner = 'account-b'; }, failApply: (fail: boolean) => { failApply = fail; } };}@@ -191,6 +197,48 @@ describe('Bot named worker transactions', () => {expect(db.prepare('SELECT count(*) FROM bot_profile_versions').pluck().get()).toBe(1);});+ it('persists a permanent save even before the first automation scope exists', async () => {+ const h = savedModelFixture();+ h.writeBaseline(null);+ h.save('permanent');+ expect(JSON.parse(h.readBaseline()!)).toMatchObject({ pendingBotProfileVersion: 2 });+ await h.reconcile()('saved-session');+ await h.scope.restore('saved-session');+ expect(h.current().model).toBe('permanent');+ });++ it.each(['save-before-begin', 'save-during-begin', 'save-after-begin'])('serializes the real scope writer and permanent save: %s', async order => {+ const h = savedModelFixture();+ h.writeBaseline(null);+ const scope = createScheduledModelScope({ ...h.scopeDeps,+ write: async (...args) => {+ if (order === 'save-during-begin') h.save('permanent');+ return h.scopeDeps.write(...args);+ },+ });+ if (order === 'save-before-begin') h.save('permanent');+ if (order === 'save-during-begin') await expect(scope.begin('saved-session')).rejects.toThrow('changed');+ else await scope.begin('saved-session');+ if (order === 'save-after-begin') h.save('permanent');+ expect(JSON.parse(h.readBaseline()!)).toMatchObject({ pendingBotProfileVersion: 2 });+ await h.reconcile()('saved-session');+ await h.scope.restore('saved-session');+ expect(h.current().model).toBe('permanent');+ expect(h.readBaseline()).toBeNull();+ });++ it('keeps begin valid across an unrelated profile edit and across a rolled-back save', async () => {+ const h = savedModelFixture();+ h.writeBaseline(null);+ const scope = createScheduledModelScope({ ...h.scopeDeps, write: async (...args) => {+ expect(() => h.save('permanent', 1, { canonicalPermissionMode: 'invalid' })).toThrow('permission mode');+ h.save('old', 1, { identitySource: 'new identity' });+ return h.scopeDeps.write(...args);+ } });+ await expect(scope.begin('saved-session')).resolves.toBe('unused');+ expect(JSON.parse(h.readBaseline()!).pendingBotProfileVersion).toBeUndefined();+ });+it('atomically rejects duplicate names and a second Cindy without touching the first profile', () => {const args = { id: 'first', displayName: 'Renamed', description: '', avatar: '🤖', avatarColor: 'blue', identitySource: 'Custom identity', capabilitiesJson: '{"templateId":"cindy"}', now: 1 };tx(db, { name: 'bots.createProfile', args });diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex 9d1461e307..ff808130b7 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@ -1,10 +1,11 @@-import { fastModeToStorage } from '@cindy/maker-shared';+import { fastModeFromStorage, fastModeToStorage } from '@cindy/maker-shared';import { runPluginUsageTransaction } from './pluginUsageTx.js';import { runTaskTagsTransaction } from './taskTagsTx.js';import { recordMediaSpend } from './mediaSpendTx.js';import { batchAutoReviewProjection, readAutoReviewProjectionTransaction } from '../../autoReviewProjection.js';import { CLOSE_SHARED_TASKS_FOR_SESSION_SQL } from '../../sharedTaskClosureSql.js';import { botProfileModelSelectionChanged } from '../../../../shared/botModelChain.js';+import { dbToMakerAgentKind } from '../../../../shared/agentKindConversion.js';import { parseScheduledModelBaseline } from '../../../../shared/scheduledModelBaseline.js';import { normalizeBotName } from '../../../../shared/botCreation.js';import { inferBotTemplatePresetId } from '../../../../shared/botTemplatePreset.js';@@ -111,6 +112,8 @@ function dispatchTransaction(db: Database.Database, args: unknown): unknown {return orcaReconcileInactiveTeamWorkersForLead(db, txArgs);case 'sessions.renameTitles':return sessionsRenameTitles(db, txArgs);+ case 'sessions.createScheduledModelBaseline':+ return sessionsCreateScheduledModelBaseline(db, txArgs);case 'sessions.setStatus':return sessionsSetStatus(db, txArgs);case 'sessions.setTerminalStatus':@@ -357,6 +360,17 @@ function botsCreateProfile(db: Database.Database, args: unknown): void {})();}+/** Atomic with Profile saves: a delayed begin cannot overwrite their pending marker. */+function sessionsCreateScheduledModelBaseline(db: Database.Database, args: unknown): boolean {+ const p = asRecord(args, 'sessions.createScheduledModelBaseline args');+ const sessionId = expectString(p.sessionId, 'sessionId');+ const baseline = expectString(p.baseline, 'baseline');+ const expected = p.expectedBaseline === null ? null : expectString(p.expectedBaseline, 'expectedBaseline');+ return db.prepare(`UPDATE sessions SET scheduled_model_baseline = ?+ WHERE id = ? AND status = 'active' AND scheduled_model_baseline IS ?`)+ .run(baseline, sessionId, expected).changes > 0;+}+function botsUpdateProfile(db: Database.Database, args: unknown): { currentVersion: number } {const p = asRecord(args, 'bots.updateProfile args');const id = expectString(p.id, 'id');@@ -445,13 +459,24 @@ function botsUpdateProfile(db: Database.Database, args: unknown): { currentVersi)) {// Save the pending choice in the same transaction as the profile. A// paused runtime may not receive its refresh before restart/account exit.- const targets = db.prepare(`SELECT id, scheduled_model_baseline AS baseline FROM sessions WHERE id IN+ const targets = db.prepare(`SELECT id, scheduled_model_baseline AS baseline,+ agent_kind AS agentKind, model, provider_id AS providerId, effort, fast_mode AS fastMode+ FROM sessions WHERE id IN(SELECT session_id FROM bot_session_links WHERE bot_id = ?- AND role IN ('canonical', 'group', 'channel', 'thread') AND archived_at IS NULL)- AND scheduled_model_baseline IS NOT NULL`).all(id) as Array<{ id: string; baseline: string }>;+ AND role IN ('canonical', 'group', 'channel', 'thread') AND archived_at IS NULL)`)+ .all(id) as Array<{ id: string; baseline: string | null; agentKind: string; model: string;+ providerId: string | null; effort: string; fastMode: number | string }>;+const update = db.prepare('UPDATE sessions SET scheduled_model_baseline = ? WHERE id = ?');for (const target of targets) {- const baseline = parseScheduledModelBaseline(target.baseline);+ // A save must also fence a begin that read a null baseline, or begins+ // before the async profile refresh. This record is never restored:+ // only acceptance of this permanent choice may consume it.+ const baseline = parseScheduledModelBaseline(target.baseline ?? JSON.stringify({+ scopeId: `${target.id}:profile:${nextVersion}`, agentKind: dbToMakerAgentKind(target.agentKind),+ model: target.model, providerId: target.providerId, effort: target.effort,+ fastMode: fastModeFromStorage(target.fastMode),+ }));if (baseline) update.run(JSON.stringify({ ...baseline, pendingBotProfileVersion: nextVersion }), target.id);}}diff --git a/apps/desktop/src/main/maker-ipc/__tests__/scheduledModelSelection.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/scheduledModelSelection.test.tsindex f95da5ead6..7ddbc8bb80 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/scheduledModelSelection.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/scheduledModelSelection.test.ts@@ -37,6 +37,19 @@ describe('one-run automation model preferences', () => {choose: () => { baseline = null; profile = { ...original, model: 'new-owner-model' }; },};}+ it('stops scope creation when a permanent save wins the baseline compare-and-set', async () => {+ const h = scopeFixture();+ const scope = createScheduledModelScope({ ...h.deps, write: async () => false });+ await expect(scope.begin('task')).rejects.toThrow('changed');+ expect(h.deps.apply).not.toHaveBeenCalled();+ });+ it('stops restoration when a permanent save wins before cleanup', async () => {+ const h = scopeFixture();+ await h.scope.begin('task');+ const scope = createScheduledModelScope({ ...h.deps, write: async () => false });+ await expect(scope.restore('task')).rejects.toThrow('changed');+ expect(h.state().baseline).not.toBeNull();+ });it.each(['same-process', 'restart'])('restores all owner settings after %s', async (mode) => {const h = scopeFixture();await h.scope.begin('task');diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 6385557636..0854a66ded 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -10993,23 +10993,34 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)effort: row.effort, fastMode: row.fastMode,} } : null;},- write: async (sessionId, baseline) => {+ write: async (sessionId, baseline, expectedBaseline) => {const owner = captureSessionRuntimeControlOwnerEpoch();- const db = getDbClient().drizzle;- const [row] = baseline ? [] : await db.select({ baseline: sessions.scheduledModelBaseline })- .from(sessions).where(eq(sessions.id, sessionId)).limit(1);- const saved = parseScheduledModelBaseline(row?.baseline);+ const client = getDbClient();+ if (baseline) {+ const written = await client.tx('sessions.createScheduledModelBaseline', {+ sessionId, baseline: JSON.stringify(baseline), expectedBaseline,+ });+ if (!sessionRuntimeControlOwnerEpochMatches(owner)) throw new Error('Account changed during scheduled model selection');+ if (written) await broadcastSessionRuntimeProjection(sessionId);+ return written;+ }+ const db = client.drizzle;+ const saved = parseScheduledModelBaseline(expectedBaseline);if (!sessionRuntimeControlOwnerEpochMatches(owner)) throw new Error('Account changed during scheduled model selection');- await db.update(sessions)+ const updated = 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,} : {}),})- .where(eq(sessions.id, sessionId));+ .where(and(eq(sessions.id, sessionId), expectedBaseline === null+ ? isNull(sessions.scheduledModelBaseline) : eq(sessions.scheduledModelBaseline, expectedBaseline)))+ .returning({ id: sessions.id });+ if (!updated.length) return false;await broadcastSessionRuntimeProjection(sessionId);+ return true;},isBusy: (sessionId) => isSessionInTurn(sessionId) || !!maker.getSession(sessionId)?.isTurnRunning() ||isUserPendingAgentSwitchIntent(agentSwitchPending.get(sessionId)),diff --git a/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts b/apps/desktop/src/main/maker-ipc/scheduledModelSelection.tsindex 4e08eb4055..fd801f9a50 100644--- a/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts+++ b/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts@@ -25,7 +25,7 @@ export function createScheduledModelScope(deps: {};baseline: string | null;} | null>;- write: (sessionId: string, baseline: ScheduledModelBaseline | null) => Promise<void>;+ write: (sessionId: string, baseline: ScheduledModelBaseline | null, expectedBaseline: string | null) => Promise<void | boolean>;isBusy: (sessionId: string) => boolean;apply: (sessionId: string, profile: ScheduledModelSelection) => Promise<void>;createId: () => string;@@ -43,7 +43,9 @@ export function createScheduledModelScope(deps: {const existing = parseScheduledModelBaseline(row.baseline);if (existing) return existing.scopeId;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 }, row.baseline);+ assertOwner(owner);+ if (written === false) throw new ScheduledModelSelectionBusyError('Scheduled model selection changed before scope creation');return scopeId;},async restore(sessionId: string, expectedScopeId?: string): Promise<void> {@@ -59,7 +61,9 @@ export function createScheduledModelScope(deps: {// Keep the saved choice on failure so the next input retries before dispatch.await deps.apply(sessionId, baseline);assertOwner(owner);- await deps.write(sessionId, null);+ const written = await deps.write(sessionId, null, row!.baseline);+ assertOwner(owner);+ if (written === false) throw new ScheduledModelSelectionBusyError('Scheduled model selection changed before scope cleanup');},};}