Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
Merge main and preserve model baselines across permission-only saves
ylliuuu6659427350a1bf
diff --cc apps/desktop/src/main/__tests__/rewindNativeBoundarySqlite.test.tsindex 22511d335c,e3eb637658..bd32932099--- a/apps/desktop/src/main/__tests__/rewindNativeBoundarySqlite.test.ts+++ b/apps/desktop/src/main/__tests__/rewindNativeBoundarySqlite.test.ts@@@ -14,18 -14,27 +14,32 @@@ import { getTableConfig } from 'drizzleimport type { DbClient } from '../localDb/client/DbClient';import { clearCurrentDbClient, setCurrentDbClient } from '../localDb/client/current';import { messages, sessions } from '../localDb/schema';+ import { commitRewindAtMessage } from '../maker-orchestration/rewind';++ // Keep the real local rewind SQL and history helpers without starting the+ // unrelated device-link host (same boundary as rewind.test.ts, #6563).+ vi.mock('../device-link/index.js', () => ({+ remoteBackgroundInvoke: () => { throw new Error('unexpected remote invocation in local rewind'); },+ }));+// Local SQL rewind reuses fork helpers without initializing the device-link host.+vi.mock('../device-link/index.js', () => ({+ remoteBackgroundInvoke: () => { throw new Error('unexpected remote invocation in local rewind'); },+}));+const commitRewindFilesMock = vi.fn();const isTurnRunningMock = vi.fn(() => false);- const recomputePrRefsForSessionMock = vi.fn();- const executeCodexFileRewindPlanWithThreadRollbackMock = vi.fn();- const executeCodexFileRestorePlanWithThreadRollbackMock = vi.fn();- const detectCwdMock = vi.fn();+ const {+ recomputePrRefsForSessionMock,+ executeCodexFileRewindPlanWithThreadRollbackMock,+ executeCodexFileRestorePlanWithThreadRollbackMock,+ detectCwdMock,+ } = vi.hoisted(() => ({+ recomputePrRefsForSessionMock: vi.fn(),+ executeCodexFileRewindPlanWithThreadRollbackMock: vi.fn(),+ executeCodexFileRestorePlanWithThreadRollbackMock: vi.fn(),+ detectCwdMock: vi.fn(),+ }));type FakeSession = {agentKind: 'codex';diff --cc apps/desktop/src/main/localDb/worker/opHandlers/__tests__/botTx.test.tsindex cb87bbed77,f14333b3e3..72c3e25380--- a/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/botTx.test.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/botTx.test.ts@@@ -55,207 -50,6 +55,253 @@@ describe('Bot named worker transactionsafterEach(() => db.close());+ // #6759: exercise the actual save transaction, then discard process-local+ // reconciliation state before IM preparation and automation restore.+ function savedModelFixture() {+ const original: ScheduledModelSelection = {+ agentKind: 'codex', model: 'old', providerId: 'connected-custom', effort: 'high', fastMode: false,+ };+ let current = { ...original, model: 'temporary' };+ let owner = 'account-a';+ const capabilities = (model: string) => JSON.stringify({ modelChain: [{+ harness: 'codex', model, providerId: 'connected-custom', effort: 'high', fastMode: false,+ }] });+ tx(db, { name: 'bots.createProfile', args: {+ id: 'saved-bot', displayName: 'Saved', description: '', avatar: '', avatarColor: 'blue',+ identitySource: 'identity', capabilitiesJson: capabilities('old'), now: 1,+ } });+ tx(db, { name: 'bots.replaceCanonicalSession', args: {+ botId: 'saved-bot', expectedCanonicalSessionId: null, expectedProfileVersion: 1,+ session: { id: 'saved-session', title: 'Saved', workingDir: '/tmp/saved-session',+ workspaceKind: 'dialogue', model: 'temporary', effort: 'high', permissionMode: 'ask',+ agentKind: 'codex', remoteHostId: null, providerId: 'connected-custom', extraDirs: '[]',+ source: 'bot', createdAt: 2, updatedAt: 2 }, now: 2,+ } });+ const readBaseline = () => db.prepare('SELECT scheduled_model_baseline FROM sessions WHERE id = ?')+ .pluck().get('saved-session') as string | null;+ const writeBaseline = (value: string | null) => {+ db.prepare('UPDATE sessions SET scheduled_model_baseline = ? WHERE id = ?').run(value, 'saved-session');+ };+ writeBaseline(JSON.stringify({ ...original, scopeId: 'automation' }));+ const pause = (paused: boolean) => {+ db.prepare('UPDATE bot_profiles SET status = ? WHERE id = ?').run(paused ? 'paused' : 'active', 'saved-bot');+ };+ const save = (model: string, expectedCurrentVersion = 1, extra: Record<string, unknown> = {}) => tx(db, {+ name: 'bots.updateProfile', args: { id: 'saved-bot', expectedCurrentVersion,+ identitySource: 'identity', capabilitiesJson: capabilities(model), profileContentChanged: true, now: 3, ...extra },+ });+ let failApply = false;+ const reconcile = () => createBotModelRouteReconciler({+ ownerEpoch: () => owner,+ read: async () => {+ const row = db.prepare(`SELECT p.status, v.capabilities_json AS capabilities FROM bot_profiles p+ JOIN bot_profile_versions v ON v.bot_id = p.id AND v.version = p.current_version+ WHERE p.id = 'saved-bot'`).get() as { status: string; capabilities: string };+ return row.status === 'active' ? {+ chain: normalizeBotModelChain(JSON.parse(row.capabilities).modelChain), current,+ hasRuntimeOverride: false, scheduledModelBaseline: readBaseline(),+ } : null;+ },+ apply: async (_id, route) => {+ if (failApply) throw new Error('provider unavailable');+ current = { ...route, effort: route.effort as ScheduledModelSelection['effort'] };+ },+ onSelectionAccepted: async () => { writeBaseline(null); },+ });+ const scopeDeps: Parameters<typeof createScheduledModelScope>[0] = {+ read: async () => ({ profile: current, baseline: readBaseline() }),+ 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',+ };+ const scope = createScheduledModelScope(scopeDeps);+ return { original, readBaseline, pause, save, reconcile, scope, scopeDeps, writeBaseline, current: () => current,+ changeOwner: () => { owner = 'account-b'; }, failApply: (fail: boolean) => { failApply = fail; } };+ }+++ // Permission-only saves can now create a Profile version without model input.++ // Exercise their intersection with the durable automation restore transaction.++ it.each([false, true])('preserves the fallback on a permission-only save (stale payload: %s)', async stalePayload => {++ const h = savedModelFixture();++ const baseline = h.readBaseline();++ expect(tx(db, { name: 'bots.updateProfile', args: {++ id: 'saved-bot', expectedCurrentVersion: 1, now: 3, profileContentChanged: false,++ canonicalPermissionMode: 'bypassPermissions',++ ...(stalePayload ? { capabilitiesJson: JSON.stringify({ model: 'stale' }) } : {}),++ } })).toEqual({ currentVersion: 2 });++ expect(h.readBaseline()).toBe(baseline);++ const saved = db.prepare('SELECT identity_source AS identity, capabilities_json AS config FROM bot_profile_versions WHERE version = 2')++ .get() as { identity: string; config: string };++ expect(saved.identity).toBe('identity');++ expect(JSON.parse(saved.config)).toMatchObject({ permissions: 'trusted', modelChain: [{ model: 'old' }] });++ expect(db.prepare('SELECT permission_mode FROM sessions').pluck().get()).toBe('bypassPermissions');++ await h.reconcile()('saved-session');++ await h.scope.restore('saved-session');++ expect(h.current()).toMatchObject(h.original);++ });++++ it('accepts a model save without reverting a newer permission choice', async () => {++ const h = savedModelFixture();++ tx(db, { name: 'bots.persistSessionPermission', args: { sessionId: 'saved-session', mode: 'bypassPermissions' } });++ h.save('permanent');++ expect(JSON.parse(h.readBaseline()!)).toMatchObject({ pendingBotProfileVersion: 2 });++ expect(JSON.parse(db.prepare('SELECT capabilities_json FROM bot_profile_versions WHERE version = 2').pluck().get() as string))++ .toMatchObject({ permissions: 'trusted' });++ await h.reconcile()('saved-session');++ await h.scope.restore('saved-session');++ expect(h.current().model).toBe('permanent');++ expect(h.readBaseline()).toBeNull();++ expect(db.prepare('SELECT permission_mode FROM sessions').pluck().get()).toBe('bypassPermissions');++ });++++ it('keeps the baseline and permission when the expected Profile version is missing', () => {++ const h = savedModelFixture();++ const baseline = h.readBaseline();++ db.prepare('DELETE FROM bot_profile_versions').run();++ expect(() => h.save('permanent', 1, { canonicalPermissionMode: 'bypassPermissions' }))++ .toThrowError(expect.objectContaining({ code: 'PRECONDITION_FAILED' }));++ expect(h.readBaseline()).toBe(baseline);++ expect(db.prepare('SELECT permission_mode FROM sessions').pluck().get()).toBe('ask');++ expect(db.prepare('SELECT current_version FROM bot_profiles').pluck().get()).toBe(1);++ });+++ it.each(['restart', 'account-change'])('accepts a paused permanent save after %s before restoring automation', async boundary => {+ const h = savedModelFixture();+ h.pause(true);+ let reconcile = h.reconcile();+ h.save('permanent');+ await reconcile.profileChanged('saved-session');+ if (boundary === 'restart') reconcile = h.reconcile();+ else h.changeOwner();+ h.pause(false);+ await reconcile('saved-session');+ await h.scope.restore('saved-session');+ expect(h.current().model).toBe('permanent');+ expect(h.readBaseline()).toBeNull();+ });++ it('accepts a same-route permanent save after restart without restoring the old provider choice', async () => {+ const h = savedModelFixture();+ h.pause(true);+ h.save('temporary');+ h.pause(false);+ await h.reconcile()('saved-session');+ await h.scope.restore('saved-session');+ expect(h.current().model).toBe('temporary');+ expect(h.readBaseline()).toBeNull();+ });++ it('keeps the durable save and old baseline on failure, without restoring it while paused', async () => {+ const h = savedModelFixture();+ h.pause(true);+ h.save('permanent');+ const pending = h.readBaseline();+ await h.scope.restore('saved-session');+ expect(h.current().model).toBe('temporary');+ expect(h.readBaseline()).toBe(pending);+ h.pause(false);+ h.failApply(true);+ await expect(h.reconcile()('saved-session')).rejects.toThrow('provider unavailable');+ expect(h.readBaseline()).toBe(pending);+ h.failApply(false);+ await h.reconcile()('saved-session');+ await h.scope.restore('saved-session');+ expect(h.current().model).toBe('permanent');+ });++ it('does not invalidate a baseline for a non-model profile edit or a rejected save', async () => {+ const h = savedModelFixture();+ const baseline = h.readBaseline();+ h.save('old', 1, { identitySource: 'new identity' });+ expect(h.readBaseline()).toBe(baseline);+ expect(() => h.save('permanent')).toThrow('Profile');+ expect(h.readBaseline()).toBe(baseline);+ await h.reconcile()('saved-session');+ await h.scope.restore('saved-session');+ expect(h.current()).toMatchObject(h.original);+ });++ it.each(['canonical', 'group', 'channel', 'thread', 'background', 'archived'])('marks only following profile links: %s', role => {+ const h = savedModelFixture();+ const baseline = h.readBaseline();+ if (role === 'archived') db.prepare('UPDATE bot_session_links SET archived_at = 4').run();+ else db.prepare('UPDATE bot_session_links SET role = ?').run(role);+ h.save('permanent');+ if (role === 'background' || role === 'archived') expect(h.readBaseline()).toBe(baseline);+ else expect(JSON.parse(h.readBaseline()!)).toMatchObject({ pendingBotProfileVersion: 2, model: 'old' });+ });++ it('rolls back the pending marker with a failed profile transaction', () => {+ const h = savedModelFixture();+ const baseline = h.readBaseline();+ expect(() => h.save('permanent', 1, { canonicalPermissionMode: 'invalid' })).toThrow('permission mode');+ expect(h.readBaseline()).toBe(baseline);+ expect(db.prepare('SELECT current_version FROM bot_profiles').pluck().get()).toBe(1);+ 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'].flatMap(order =>+ [null, '{broken'].map(initialBaseline => ({ order, initialBaseline })),+ ))('serializes the real scope writer and permanent save: $order / $initialBaseline', async ({ order, initialBaseline }) => {+ const h = savedModelFixture();+ h.writeBaseline(initialBaseline);+ 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('preserves runtime fallback when a non-model edit normalizes a legacy chain-only profile', async () => {+ const h = savedModelFixture();+ const fallback = { ...h.original, model: 'runtime-fallback', scopeId: 'automation' };+ h.writeBaseline(JSON.stringify(fallback));+ const previous = JSON.parse(db.prepare('SELECT capabilities_json FROM bot_profile_versions').pluck().get() as string);+ expect(previous.model).toBeUndefined();+ const next = normalizeBotProfileModelChain({ ...previous, skills: ['new-skill'] });+ h.save('old', 1, { capabilitiesJson: JSON.stringify(next), identitySource: 'edited identity' });+ expect(h.readBaseline()).toBe(JSON.stringify(fallback));+ await h.reconcile()('saved-session');+ await h.scope.restore('saved-session');+ expect(h.current().model).toBe('runtime-fallback');+ });+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 --cc apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex 6553e0c3fd,f35036ce1e..66d46ccde2--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@@ -450,36 -462,8 +478,32 @@@ function botsUpdateProfile(db: Databasedb.prepare(`INSERT INTO bot_profile_versions(id, bot_id, version, identity_source, capabilities_json, created_at)VALUES (?, ?, ?, ?, ?, ?)`)- .run(`${id}:v${nextVersion}`, id, nextVersion, expectString(p.identitySource, 'identitySource'),- expectString(p.capabilitiesJson, 'capabilitiesJson'), now);- const previous = db.prepare('SELECT capabilities_json AS capabilities FROM bot_profile_versions WHERE bot_id = ? AND version = ?')- .get(id, expectedVersion) as { capabilities: string } | undefined;- if (botProfileModelSelectionChanged(- parsedObjectJson(previous?.capabilities ?? null) ?? {}, parsedObjectJson(expectString(p.capabilitiesJson, 'capabilitiesJson')) ?? {},- )) {+ .run(`${id}:v${nextVersion}`, id, nextVersion, p.identitySource === undefined ? latest!.identity : expectString(p.identitySource, 'identitySource'),+ JSON.stringify(nextConfig), now);++ if (botProfileModelSelectionChanged(latestConfig ?? {}, nextConfig ?? {})) {+ // 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,+ 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)`)+ .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) {+ // 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) ?? parseScheduledModelBaseline(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);+ }+ }// Hermes capability epoch: the permanent canonical Chat, the Bot's// group-chat lanes and its IM channel lanes follow the latest Profile on// their next runtime bootstrap. Route/worker links remain pinned to their