Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
Merge upstream main and preserve companion model and permission ordering
Chrisbbacaa39a378
diff --cc apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex 72623aef59,a4b610104c..9817d638e0--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@@ -9859,110 -10042,6 +10046,113 @@@ describe('Bot self control uses the samdescribe('Teammate model selection shares profile persistence and route reconciliation', () => {+ // #6895 P1: the previous crash test stopped at the profile commit. A subsequent+ // automation could recreate A before runtime refresh. DB tier: exercise the+ // real save transaction, send locks, reconciler and baseline writer in both+ // orders, then restore through a fresh scope (no runtime refresh or timers).+ it.each(['save-first', 'automation-first'] as const)('does not resurrect an old route when %s races baseline capture', async (order) => {+ const created = await invoke('local-db:bots:create-canonical-session', {+ botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1,+ });+ 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 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 = ?')+ .run(route.agentKind, route.model, route.providerId, route.effort ?? '', Number(route.fastMode), sessionId);+ };+ const reconcile = createBotModelRouteReconciler({ ownerEpoch: () => h.ownerScopeKey,+ withSessionLock: withSendToSessionLock,+ read: async () => {+ const state = await read();+ const bot = await invoke('local-db:bots:get', 'bot-1');+ return { chain: await modelSettings.readEffectiveBotModelChain(bot.capabilities),+ current: state.profile, hasRuntimeOverride: true,+ scheduledModelBaseline: state.baseline ? JSON.parse(state.baseline) : null };+ }, apply,+ });+ let savingReachedLock!: () => void;+ const waiting = new Promise<void>((resolve) => { savingReachedLock = resolve; });+ configureBotModelSelectionCoordinator(createBotModelSelectionCoordinator({+ acquireSessionLock: (id) => { savingReachedLock(); return acquireSendToSessionLock(id); },+ invalidate: reconcile.invalidate,+ }));+ const deps = { read, apply, isBusy: () => false, createId: () => 'race-scope',+ prepareBaseline: (id: string) => reconcile(id, true),+ write: async (_id: string, baseline: unknown) => {+ h.sqlite!.prepare('UPDATE sessions SET scheduled_model_baseline = ? WHERE id = ?')+ .run(baseline ? JSON.stringify(baseline) : null, sessionId);+ },+ };+ const scope = createScheduledModelScope(deps);+ const save = () => invoke('local-db:bots:update', { id: 'bot-1', capabilities: {++ // Combined settings also enter the permission commit fence from #6782.++ permissions: 'auto',+ modelChainOverride: [{ harness: 'codex', model: 'new-saved-model', providerId: null, effort: 'medium', fastMode: false }],+ } });+ if (order === 'automation-first') {+ const release = await acquireSendToSessionLock(sessionId);+ const saving = save();+ try {+ await waiting;+ await scope.begin(sessionId);+ expect(JSON.parse((await read()).baseline!).model).not.toBe('new-saved-model');+ } finally { release(); }+ await saving;+ expect((await read()).baseline).toBeNull();+ } else {+ await save();+ }++ expect(h.sqlite!.prepare('SELECT permission_mode FROM sessions WHERE id = ?').pluck().get(sessionId)).toBe('auto');+ // requestRuntimeRefresh is inert in this fixture: begin must align the saved+ // route itself rather than relying on the asynchronous refresh continuation.+ await withSendToSessionLock(sessionId, () => scope.begin(sessionId));+ expect(JSON.parse((await read()).baseline!)).toMatchObject({ agentKind: 'codex', model: 'new-saved-model' });+ await apply(sessionId, { agentKind: 'pi', model: 'temporary', providerId: null, effort: null, fastMode: false });+ await withSendToSessionLock(sessionId, () => createScheduledModelScope(deps).restore(sessionId));+ expect((await read()).profile).toMatchObject({ agentKind: 'codex', model: 'new-saved-model' });+ expect((await read()).baseline).toBeNull();+ });++ // #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 () => {+ const created = await invoke('local-db:bots:create-canonical-session', {+ botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1,+ });+ const sessionId = created.session.id;+ const baseline = JSON.stringify({ scopeId: 'automation', agentKind: 'pi', model: 'old-model', providerId: null, effort: null, fastMode: false });+ h.sqlite!.prepare('UPDATE sessions SET scheduled_model_baseline = ? WHERE id = ?').run(baseline, sessionId);+ const readBaseline = () => (h.sqlite!.prepare('SELECT scheduled_model_baseline AS baseline FROM sessions WHERE id = ?').get(sessionId) as { baseline: string | null }).baseline;+ await invoke('local-db:bots:update', { id: 'bot-1', name: 'Renamed companion' });+ expect(readBaseline()).toBe(baseline);+ h.requestRuntimeRefresh.mockClear();+ const runTx = h.tx!;+ h.tx = async (name, args) => {+ const result = await runTx(name, args);+ if (name === 'bots.updateProfile') throw new Error('simulated process loss after commit');+ return result;+ };+ await expect(invoke('local-db:bots:update', { id: 'bot-1', capabilities: {+ modelChainOverride: [{ harness: 'codex', model: 'new-saved-model', providerId: null, effort: 'medium', fastMode: false }],+ } })).rejects.toThrow('simulated process loss after commit');+ expect(h.requestRuntimeRefresh).not.toHaveBeenCalled();+ expect(readBaseline()).toBeNull();+ const profile = await invoke('local-db:bots:get', 'bot-1');+ const chain = await modelSettings.readEffectiveBotModelChain(profile.capabilities);+ const apply = vi.fn();+ const cold = createBotModelRouteReconciler({ ownerEpoch: () => h.ownerScopeKey,+ read: async () => ({ chain, current: { agentKind: 'pi', model: 'temporary-model', providerId: null, effort: null, fastMode: false },+ scheduledModelBaseline: readBaseline() ? JSON.parse(readBaseline()!) : null, hasRuntimeOverride: false }), apply,+ });+ expect(await cold.preview(sessionId)).toMatchObject({ agentKind: 'codex', model: 'new-saved-model' });+ await cold(sessionId);+ expect(apply).toHaveBeenCalledWith(sessionId, expect.objectContaining({ agentKind: 'codex', model: 'new-saved-model' }), expect.anything());+ });+async function setupModelControl() {const canonical = await invoke('local-db:bots:create-canonical-session', {botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1,diff --cc apps/desktop/src/main/localDb/ipc/bots.tsindex 9fae2d11e2,fd0f0933d7..d1245b7297--- a/apps/desktop/src/main/localDb/ipc/bots.ts+++ b/apps/desktop/src/main/localDb/ipc/bots.ts@@@ -1997,58 -2024,67 +2026,76 @@@ export async function updateBotProfile(owner.assertCurrent();const changesPermissions = body.capabilities != null && typeof body.capabilities === 'object'&& Object.prototype.hasOwnProperty.call(body.capabilities, 'permissions');+ const modelFollowers = modelSelectionChanged ? await db.select({ sessionId: botSessionLinks.sessionId })+ .from(botSessionLinks).where(and(eq(botSessionLinks.botId, id),+ inArray(botSessionLinks.role, ['canonical', 'group', 'channel', 'thread']),+ isNull(botSessionLinks.archivedAt))) : [];- await coordinateBotModelSelection(modelFollowers.map((link) => link.sessionId), async () => {- // Lock acquisition can wait behind an automation. Recheck the account before- // committing; the worker still owns the profile-version CAS and atomic clear.- owner.assertCurrent();- await client.tx('bots.updateProfile', {- id,- ...(modelSelectionChanged ? { clearScheduledModelBaseline: true } : {}),- ...(changesPermissions ? { canonicalPermissionMode: botSessionPermissionMode(normalizedNextConfig) } : {}),- ...(patch.displayName !== undefined ? { displayName: patch.displayName } : {}),- ...(patch.description !== undefined ? { description: patch.description } : {}),- ...(patch.avatar !== undefined ? { avatar: patch.avatar } : {}),- ...(patch.avatarColor !== undefined ? { avatarColor: patch.avatarColor } : {}),- ...(patch.status !== undefined ? { status: patch.status } : {}),- ...(hiddenAt !== undefined ? { hiddenAt } : {}),- ...(pinnedAt !== undefined ? { pinnedAt } : {}),- identitySource: nextIdentitySource,- capabilitiesJson: safeJson(normalizedNextConfig),- profileContentChanged,- expectedCurrentVersion: current.currentVersion,- clearBotAvatarRefs:- patch.avatar !== undefined &&- isManagedBotAvatarUrl(current.avatar) &&- !isManagedBotAvatarUrl(patch.avatar),- now,+ const commitProfile = async () => {- owner.assertCurrent();- await client.tx('bots.updateProfile', {- id,- ...(changesPermissions ? { canonicalPermissionMode: botSessionPermissionMode(normalizedNextConfig) } : {}),- ...(patch.displayName !== undefined ? { displayName: patch.displayName } : {}),- ...(patch.description !== undefined ? { description: patch.description } : {}),- ...(patch.avatar !== undefined ? { avatar: patch.avatar } : {}),- ...(patch.avatarColor !== undefined ? { avatarColor: patch.avatarColor } : {}),- ...(patch.status !== undefined ? { status: patch.status } : {}),- ...(hiddenAt !== undefined ? { hiddenAt } : {}),- ...(pinnedAt !== undefined ? { pinnedAt } : {}),- identitySource: nextIdentitySource,- capabilitiesJson: safeJson(normalizedNextConfig),- profileContentChanged,- expectedCurrentVersion: current.currentVersion,- clearBotAvatarRefs:- patch.avatar !== undefined &&- isManagedBotAvatarUrl(current.avatar) &&- !isManagedBotAvatarUrl(patch.avatar),- now,++ await coordinateBotModelSelection(modelFollowers.map((link) => link.sessionId), async () => {++ // Hold send locks only through persistence/invalidation, not runtime++ // permission refresh, which may wait for the current turn to finish.++ owner.assertCurrent();++ await client.tx('bots.updateProfile', {++ id,++ ...(modelSelectionChanged ? { clearScheduledModelBaseline: true } : {}),++ ...(changesPermissions ? { canonicalPermissionMode: botSessionPermissionMode(normalizedNextConfig) } : {}),++ ...(patch.displayName !== undefined ? { displayName: patch.displayName } : {}),++ ...(patch.description !== undefined ? { description: patch.description } : {}),++ ...(patch.avatar !== undefined ? { avatar: patch.avatar } : {}),++ ...(patch.avatarColor !== undefined ? { avatarColor: patch.avatarColor } : {}),++ ...(patch.status !== undefined ? { status: patch.status } : {}),++ ...(hiddenAt !== undefined ? { hiddenAt } : {}),++ ...(pinnedAt !== undefined ? { pinnedAt } : {}),++ identitySource: nextIdentitySource,++ capabilitiesJson: safeJson(normalizedNextConfig),++ profileContentChanged,++ expectedCurrentVersion: current.currentVersion,++ clearBotAvatarRefs:++ patch.avatar !== undefined &&++ isManagedBotAvatarUrl(current.avatar) &&++ !isManagedBotAvatarUrl(patch.avatar),++ now,++ });});- });- owner.assertCurrent();- if (changesPermissions) {- // Read the committed canonical row: profile and chat permissions change together,- // and a concurrent newer settings save must not be rolled back by this continuation.- const [canonical] = await db.select({ sessionId: botSessionLinks.sessionId, mode: sessions.permissionMode })- .from(botSessionLinks).innerJoin(sessions, eq(sessions.id, botSessionLinks.sessionId))- .where(and(eq(botSessionLinks.botId, id), eq(botSessionLinks.role, 'canonical'), isNull(botSessionLinks.archivedAt))).limit(1);owner.assertCurrent();- if (canonical) {- const maker = getMakerIfReady();- const live = maker?.getSession(canonical.sessionId);- try { await live?.setPermissionMode(canonical.mode as 'ask' | 'auto' | 'bypassPermissions'); }- catch (error) {- // A failed hot switch cannot leave the old, more permissive runtime alive.+ if (changesPermissions) {+ // Read the committed canonical row: profile and chat permissions change together,+ // and a concurrent newer settings save must not be rolled back by this continuation.+ const [canonical] = await db.select({ sessionId: botSessionLinks.sessionId, mode: sessions.permissionMode })+ .from(botSessionLinks).innerJoin(sessions, eq(sessions.id, botSessionLinks.sessionId))+ .where(and(eq(botSessionLinks.botId, id), eq(botSessionLinks.role, 'canonical'), isNull(botSessionLinks.archivedAt))).limit(1);+ owner.assertCurrent();+ try {+ if (canonical) {+ const maker = getMakerIfReady();+ const live = maker?.getSession(canonical.sessionId);+ try { await live?.setPermissionMode(canonical.mode as 'ask' | 'auto' | 'bypassPermissions'); }+ catch (error) {+ // A failed hot switch cannot leave the old, more permissive runtime alive.+ owner.assertCurrent();+ if (maker?.getSession(canonical.sessionId) === live) await maker?.closeSession(canonical.sessionId);+ throw error;+ }+ owner.assertCurrent();+ broadcastSessionPatched(canonical.sessionId, { permissionMode: canonical.mode });+ }+ } finally {owner.assertCurrent();- if (maker?.getSession(canonical.sessionId) === live) await maker?.closeSession(canonical.sessionId);- throw error;+ await syncBotPermissionsByBotId(id, canonical?.sessionId);}- owner.assertCurrent();- broadcastSessionPatched(canonical.sessionId, { permissionMode: canonical.mode });}- }+ };+ if (changesPermissions) {+ const [canonical] = await db.select({ sessionId: botSessionLinks.sessionId }).from(botSessionLinks)+ .where(and(eq(botSessionLinks.botId, id), eq(botSessionLinks.role, 'canonical'), isNull(botSessionLinks.archivedAt))).limit(1);+ owner.assertCurrent();+ // Serialize the DB commit and runtime continuation together with the chat+ // permission chip; native Session serialization alone only orders transports.+ await withBotPermissionChangeForBot(id, async () => {+ if (canonical) await withSessionPermissionChange(canonical.sessionId, commitProfile);+ else await commitProfile();+ });+ } else await commitProfile();// The files are the user's editing surface: rewrite only the file whose content this// save changed, so pinning, a model change or editing the other file cannot clobber// hand edits that have not been reconciled yet.diff --cc apps/desktop/src/main/localDb/worker/opHandlers/__tests__/botTx.test.tsindex 4051882d56,f14333b3e3..b4a02ef527--- a/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/botTx.test.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/botTx.test.ts@@@ -130,36 -130,34 +130,68 @@@ describe('Bot named worker transactions).toEqual({ hiddenAt: null, pinnedAt: null });});+ // #6895: model saves must retire only live profile-following restores, and+ // a later write failure must roll back both the profile and the restore clear.+ it('retires only active profile-following restores atomically with the model save', () => {+ tx(db, { name: 'bots.createProfile', args: {+ id: 'bot-1', displayName: 'Hermes', description: '', avatar: '🤖', avatarColor: 'violet',+ identitySource: 'identity', capabilitiesJson: '{}', now: 1,+ } });+ for (const role of ['canonical', 'group', 'channel', 'thread', 'worker', 'archived']) {+ db.prepare(`INSERT INTO sessions+ (id, title, workspace_kind, model, effort, permission_mode, status, total_token_usage,+ total_cost_usd, context_tokens, context_window, fast_mode, plan_mode_enabled, agent_kind,+ extra_dirs, source, created_at, updated_at, scheduled_model_baseline)+ VALUES (?, 'Hermes', 'dialogue', 'temporary', 'high', 'ask', 'active',+ 0, 0, 0, 0, 0, 0, 'codex', '[]', 'bot', 2, 2, 'old-route')`).run(role);+ db.prepare(`INSERT INTO bot_session_links+ (id, bot_id, session_id, profile_version, role, created_at, archived_at)+ VALUES (?, 'bot-1', ?, 1, ?, 2, ?)`).run(`link-${role}`, role, role === 'archived' ? 'channel' : role, role === 'archived' ? 3 : null);+ }+ const args = { id: 'bot-1', identitySource: 'identity', capabilitiesJson: '{"model":"new"}',+ profileContentChanged: true, expectedCurrentVersion: 1, clearScheduledModelBaseline: true, now: 4 };- // The permission write follows restore retirement in this existing transaction.- expect(() => tx(db, { name: 'bots.updateProfile', args: { ...args, canonicalPermissionMode: 'invalid' } }))- .toThrow('Invalid canonical permission mode');++ // Fail the permission write after restore retirement, not its early input++ // validation, so this still verifies rollback of the combined transaction.++ db.exec(`CREATE TRIGGER reject_permission_write BEFORE UPDATE OF permission_mode ON sessions++ BEGIN SELECT RAISE(ABORT, 'permission write failed'); END`);++ expect(() => tx(db, { name: 'bots.updateProfile', args: { ...args, canonicalPermissionMode: 'auto' } }))++ .toThrow('permission write failed');+ expect(db.prepare('SELECT current_version FROM bot_profiles').pluck().get()).toBe(1);+ expect(db.prepare('SELECT COUNT(*) FROM sessions WHERE scheduled_model_baseline IS NOT NULL').pluck().get()).toBe(6);++ db.exec('DROP TRIGGER reject_permission_write');+ tx(db, { name: 'bots.updateProfile', args });+ expect(db.prepare('SELECT id FROM sessions WHERE scheduled_model_baseline IS NOT NULL ORDER BY id').pluck().all())+ .toEqual(['archived', 'worker']);+ expect(db.prepare('SELECT current_version FROM bot_profiles').pluck().get()).toBe(2);+ });+ // #6782: production worker transactions; unit tier. Existing tests do not+ // interleave a composer permission commit with a settings save captured earlier.+ it.each([['ask', 'bypassPermissions', 'trusted'], ['trusted', 'ask', 'ask']])(+ 'keeps the explicit permission when an older model save lands afterwards (%s → %s)',+ (previousPermission, mode, expectedPermission) => {+ tx(db, { name: 'bots.createProfile', args: {+ id: 'bot-1', displayName: 'Hermes', description: '', avatar: '🤖', avatarColor: 'violet',+ identitySource: 'identity', capabilitiesJson: JSON.stringify({ permissions: previousPermission, model: 'old' }), now: 1,+ } });+ db.prepare(`INSERT INTO sessions+ (id, title, workspace_kind, model, effort, permission_mode, status, total_token_usage,+ total_cost_usd, context_tokens, context_window, fast_mode, plan_mode_enabled, agent_kind,+ extra_dirs, source, created_at, updated_at)+ VALUES ('canonical', 'Hermes', 'dialogue', 'model', 'high', 'ask', 'active',+ 0, 0, 0, 0, 0, 0, 'cc', '[]', 'bot', 2, 2)`).run();+ db.prepare(`INSERT INTO bot_session_links+ (id, bot_id, session_id, profile_version, role, created_at)+ VALUES ('link', 'bot-1', 'canonical', 1, 'canonical', 2)`).run();+ tx(db, { name: 'bots.persistSessionPermission', args: { sessionId: 'canonical', mode } });+ tx(db, { name: 'bots.updateProfile', args: {+ id: 'bot-1', expectedCurrentVersion: 1, profileContentChanged: true,+ identitySource: 'identity', capabilitiesJson: JSON.stringify({ permissions: previousPermission, model: 'new' }), now: 3,+ } });+ expect(JSON.parse(db.prepare('SELECT capabilities_json FROM bot_profile_versions WHERE version = 2').pluck().get() as string))+ .toEqual({ permissions: expectedPermission, model: 'new' });+ expect(db.prepare("SELECT permission_mode FROM sessions WHERE id = 'canonical'").pluck().get()).toBe(mode);+ },+ );it('creates a local-first profile and keeps one permanent canonical Session', () => {tx(db, { name: 'bots.createProfile', args: {diff --cc apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex 24bf2d672d,f35036ce1e..d4d38608b9--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@@ -447,17 -472,8 +475,16 @@@ function botsUpdateProfile(db: DatabaseWHERE bot_id = ? AND role IN ('canonical', 'group', 'channel', 'thread') AND archived_at IS NULL`).run(nextVersion, id);}+ if (p.clearScheduledModelBaseline === true) {+ // Persist the user's new model intent atomically with the profile. A crash+ // before runtime refresh must not revive the superseded automation restore.+ // Frozen delegated tasks and archived lanes retain their own selection.+ db.prepare(`UPDATE sessions SET scheduled_model_baseline = NULL 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)`)+ .run(id);+ }- if (p.canonicalPermissionMode !== undefined) {- const mode = expectString(p.canonicalPermissionMode, 'canonicalPermissionMode');- if (!['ask', 'auto', 'bypassPermissions'].includes(mode)) throw new Error('Invalid canonical permission mode');+ if (permissionMode !== undefined) {+ const mode = permissionMode;// Group and IM channel lanes run under the same permission profile as the// Bot's canonical Chat (per-turn group policies still apply on top).db.prepare(`UPDATE sessions SET permission_mode = ? WHERE id INdiff --cc apps/desktop/src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.tsindex 629cef76f7,f9dd4e6f87..503a73de61--- a/apps/desktop/src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.ts@@@ -185,8 -181,8 +185,9 @@@ function botTaskDispatchHarnesssessionQueueOriginForDispatcher: noop,extractPlainText: (value: unknown) => String(value ?? ''),assertReviewExternalInputAllowed: asyncNoop,+ syncBotLanePermission: asyncNoop,reconcileBotModelRoute: asyncNoop,+ scheduledModelScope: { restore: asyncNoop },refreshBotCapabilityEpochBeforeSend: asyncNoop,assertSessionNotRestarting: noop,sendToSessionLocks: new Map(),diff --cc apps/desktop/src/main/maker-ipc/register.tsindex f3fe8a7ad4,ede69bd2ab..bf547119ca--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@@ -11609,8 -11597,7 +11620,9 @@@ export function registerMakerIpc(makermessage: error instanceof Error ? error.message : String(error),};}+ const shadowed = await rejectShadowedCompanion(targetSessionId);+ if (shadowed) return shadowed;+ await syncBotLanePermission(targetSessionId);await reconcileBotModelRoute(targetSessionId);const compactedRuntime = maker.getSession(targetSessionId);if (compactedRuntime) await refreshBotCapabilityEpochBeforeSend(compactedRuntime);