Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): keep linked permissions aligned across profile saves
xuzini-xzn4de950b161ca
diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.tsindex 237e62c463..2b0a89de56 100644--- a/apps/desktop/src/main/localDb/client/tx/types.ts+++ b/apps/desktop/src/main/localDb/client/tx/types.ts@@ -56,6 +56,7 @@ export type DbTxName =| 'bots.archiveLifecycle'| 'bots.deleteProfile'| 'bots.prepareProfileDeletion'+ | 'bots.reconcileLanePermission'| 'bots.persistSessionPermission'| 'bots.createGroupLane'| 'bots.createChannelLane'@@ -1434,6 +1435,7 @@ export type DbTxArgsByName = {'bots.archiveLifecycle': BotsArchiveLifecycleArgs;'bots.deleteProfile': BotsDeleteProfileArgs;'bots.prepareProfileDeletion': { botId: string };+ 'bots.reconcileLanePermission': { sessionId: string };'bots.persistSessionPermission': { sessionId: string; mode: string };'bots.createGroupLane': BotGroupsCreateLaneArgs;'bots.createChannelLane': BotsCreateChannelLaneArgs;@@ -1533,6 +1535,7 @@ export type DbTxResultByName = {'bots.archiveLifecycle': { sessions: number };'bots.deleteProfile': { sessionIds: string[]; status: 'archived' | 'deleted' };'bots.prepareProfileDeletion': undefined;+ 'bots.reconcileLanePermission': { mode: string | null; changed: boolean };'bots.persistSessionPermission': { updated: boolean };'bots.createGroupLane': BotGroupsCreateLaneResult;'bots.createChannelLane': BotGroupsCreateLaneResult;diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex c4bf8f78e5..fe39a4512a 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -34,6 +34,8 @@ import { buildBotMcpCatalog } from '../../../maker-host/botMcpCatalog';import { CustomMcpProvider } from '../../../mcp-integrations/custom-mcp-provider';import type { McpProvider } from '@cindy/maker-core';import type { CustomMcpConfig } from '../../../../shared/customMcp';+import { Session } from '@cindy/maker-core';+import { withSessionPermissionChange } from '../../../maker-ipc/sessionPermissionChange';import { getMaker, getPluginRegistry, isBotToolsetAvailable } from '../../../maker-host/index';import { getBuiltinMcpServerNames, refreshCustomMcpProviders, registerCustomMcpArrays, resetCustomMcpRegistry } from '../../../mcp-integrations/custom-mcp-registry';import { isBotToolsetAvailableOnTarget } from '../../../../shared/botRemoteCapabilities';@@ -90,7 +92,7 @@ const h = await vi.hoisted(async () => {remove: vi.fn(async (_path: import('node:fs').PathLike, _options?: import('node:fs').RmOptions) => undefined),ensureGit: vi.fn(async () => undefined),closeSession: vi.fn(async () => undefined),- getSession: vi.fn(() => null as {+ getSession: vi.fn((_id?: string) => null as {capabilities?: { manualCompact?: { supported?: boolean } };isTurnRunning?: () => boolean;compactSession: (instructions?: string) => Promise<unknown>;@@ -141,7 +143,22 @@ vi.mock('electron', () => ({dialog: { showOpenDialog: h.showOpenDialog },}));vi.mock('../../client/current', () => ({- getCurrentDbClientSnapshot: () => h,+ getCurrentDbClientSnapshot: (() => {+ let current: { key: string; client: {+ tx: (name: string, args: unknown) => Promise<unknown>;+ query: (sql: string, params: unknown[]) => Promise<unknown[]>;+ } } | null = null;+ return () => {+ if (!current || current.key !== h.ownerScopeKey) current = {+ key: h.ownerScopeKey,+ client: {+ tx: (name, args) => h.tx!(name, args),+ query: async (sql, params) => h.sqlite!.prepare(sql).all(...params),+ },+ };+ return current;+ };+ })(),getDbClient: () => ({ drizzle: h.db, tx: h.tx }),tryGetDbClient: () => ({ drizzle: h.db, tx: h.tx }),}));@@ -922,6 +939,103 @@ describe('Bot canonical Session lifecycle', () => {expect(h.sqlite!.prepare('SELECT permission_mode AS mode FROM sessions WHERE id = ?').get(created.session.id)).toEqual({ mode });});+ // #6782, unit: real settings IPC and worker transaction. Earlier coverage did+ // not commit a composer permission between the profile read and settings save.+ it.each([['ask', 'bypassPermissions', 'trusted'], ['trusted', 'ask', 'ask']])(+ 'preserves a newer permission through an in-flight profile edit (%s -> %s)',+ async (previous, mode, expected) => {+ const initial = await invoke('local-db:bots:update', { id: 'bot-1', capabilities: { permissions: previous } });+ const created = await invoke('local-db:bots:create-canonical-session', {+ botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: initial.currentVersion,+ });+ const lane = await ensureBotChannelLaneSession({ botId: 'bot-1', routeKey: 'im:feishu:fixture:g:1', title: 'Fixture' });+ if (!lane.ok) throw new Error(lane.message);+ const runTx = h.tx!;+ let interleaved = false;+ h.tx = async (name, args) => {+ if (name === 'bots.updateProfile' && !interleaved) {+ interleaved = true;+ await runTx('bots.persistSessionPermission', { sessionId: created.session.id, mode });+ }+ return runTx(name, args);+ };+ const updated = await invoke('local-db:bots:update', { id: 'bot-1', name: 'Edited name' });+ expect(interleaved).toBe(true);+ expect(updated).toMatchObject({ name: 'Edited name', capabilities: { permissions: expected } });+ expect(h.sqlite!.prepare('SELECT permission_mode FROM sessions WHERE id IN (?, ?)').pluck().all(created.session.id, lane.sessionId))+ .toEqual([mode, mode]);+ const next = await ensureBotChannelLaneSession({ botId: 'bot-1', routeKey: 'im:feishu:fixture:g:2', title: 'New fixture' });+ if (!next.ok) throw new Error(next.message);+ expect(h.sqlite!.prepare('SELECT permission_mode FROM sessions WHERE id = ?').pluck().get(next.sessionId)).toBe(mode);+ },+ );++ // #6782, unit: an explicit idempotent edit is still a new permission intent.+ // The previous diff only protected changed=true profile saves.+ it('commits an explicit same-value permission after a concurrent composer choice', async () => {+ await invoke('local-db:bots:update', { id: 'bot-1', capabilities: { permissions: 'ask' } });+ const initial = await invoke('local-db:bots:get', 'bot-1');+ const created = await invoke('local-db:bots:create-canonical-session', {+ botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: initial.currentVersion,+ });+ const lane = await ensureBotChannelLaneSession({ botId: 'bot-1', routeKey: 'im:feishu:fixture:g:1', title: 'Fixture' });+ if (!lane.ok) throw new Error(lane.message);+ const runTx = h.tx!;+ let interleaved = false;+ h.tx = async (name, args) => {+ if (name === 'bots.updateProfile' && !interleaved) {+ interleaved = true;+ await runTx('bots.persistSessionPermission', { sessionId: created.session.id, mode: 'bypassPermissions' });+ }+ return runTx(name, args);+ };+ const updated = await invoke('local-db:bots:update', { id: 'bot-1', capabilities: { permissions: 'ask' } });+ expect(updated.capabilities.permissions).toBe('ask');+ expect(h.sqlite!.prepare('SELECT permission_mode FROM sessions WHERE id IN (?, ?)').pluck().all(created.session.id, lane.sessionId))+ .toEqual(['ask', 'ask']);+ });++ // Actual Session serialization alone cannot order the surrounding DB commits.+ it('orders complete settings and composer permission commits with a real Session', async () => {+ const created = await invoke('local-db:bots:create-canonical-session', {+ botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1,+ });+ let release!: () => void;+ let entered!: () => void;+ let validated!: () => void;+ const pending = new Promise<void>(resolve => { release = resolve; });+ const started = new Promise<void>(resolve => { entered = resolve; });+ const preflight = new Promise<void>(resolve => { validated = resolve; });+ const logger = { info() {}, debug() {}, trace() {}, warn() {}, error() {}, fatal() {}, child() { return logger; } };+ const live = new Session({ id: created.session.id, agentKind: 'codex', workDir: created.session.workingDir,+ permissionMode: 'ask', turnStallMs: 0, logger,+ capabilities: { permissionModes: [{ id: 'ask' }, { id: 'bypassPermissions' }], setPermissionModeMidSession: { supported: true } } as never,+ handle: { setInteractionResolver() {}, close: async () => {}, setPermissionMode: async (mode: string) => {+ if (mode === 'bypassPermissions') { entered(); await pending; }+ } } as never,+ });+ h.getSession.mockImplementation(id => id === live.id ? live as never : null);+ const composer = withSessionPermissionChange(live.id, async () => {+ await live.setPermissionMode('bypassPermissions');+ await h.tx!('bots.persistSessionPermission', { sessionId: live.id, mode: 'bypassPermissions' });+ });+ await started;+ h.validateCapabilityAdditions.mockImplementationOnce(async () => { validated(); });+ const settings = invoke('local-db:bots:update', { id: 'bot-1', name: 'Edited name', capabilities: { permissions: 'ask' } });+ await preflight;+ // Let continuations already released by the completed validation reach either+ // the native queue or the host commit fence; no wall-clock sleep is involved.+ await new Promise<void>(resolve => setImmediate(resolve));+ release();+ try {+ await Promise.all([composer, settings]);+ expect(live.stablePermissionModeState?.mode).toBe('ask');+ expect(h.sqlite!.prepare('SELECT permission_mode FROM sessions WHERE id = ?').pluck().get(live.id)).toBe('ask');+ const profile = await invoke('local-db:bots:get', 'bot-1');+ expect(profile.capabilities.permissions).toBe('ask');+ } finally { await live.close(); }+ });+it('retires a runtime whose permission change failed and keeps the saved setting for restart', async () => {const created = await invoke('local-db:bots:create-canonical-session', {botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1,@@ -2248,32 +2362,40 @@ describe('Bot canonical Session lifecycle', () => {// memory/Skill index. Exercise hydrate + persisted applied snapshots, not hash// implementation details; the minimal mutation keeps Profile and paths fixed.it.each(['canonical', 'channel', 'thread'])('refreshes shared learned resources in a running %s chat', async role => {- const created = await invoke('local-db:bots:create-canonical-session', {- botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1,- });- h.sqlite!.prepare('UPDATE bot_session_links SET role=? WHERE session_id=?').run(role, created.session.id);- const makeOpts = (): MakerSessionCreateOpts => ({- id: created.session.id, agentKind: 'codex', workingDir: created.session.workingDir,- workspaceKind: 'dialogue', model: 'gpt-5', permissionMode: 'bypassPermissions',- });- let index = '# Memory\n';- let updatedAt = 'v1';- const deps = {- readMemoryIndex: async () => index,- listOwnSkills: async () => ({ pluginRoot: '/skills', skills: [{- name: 'report', description: 'A verified report format', path: '/skills/report', updatedAt,- }] }),- };- const initial = await hydrateBotProfileRuntime(makeOpts(), deps);- await markBotProfileRuntimeApplied(initial!);- expect((await hydrateBotProfileRuntime(makeOpts(), deps))?.runtimeEpochChanged).toBe(false);- index += '- [Conclusion first](feedback_conclusion.md)\n';- const changed = await hydrateBotProfileRuntime(makeOpts(), deps);- expect(changed?.runtimeEpochChanged).toBe(true);- await markBotProfileRuntimeApplied(changed!);- expect((await hydrateBotProfileRuntime(makeOpts(), deps))?.runtimeEpochChanged).toBe(false);- updatedAt = 'v2';- expect((await hydrateBotProfileRuntime(makeOpts(), deps))?.runtimeEpochChanged).toBe(true);+ // Model successive completed bootstraps at distinct persisted times. Real+ // millisecond ties otherwise make the existing latest-snapshot query arbitrary.+ let now = Date.now();+ const clock = vi.spyOn(Date, 'now').mockImplementation(() => ++now);+ try {+ const created = await invoke('local-db:bots:create-canonical-session', {+ botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1,+ });+ h.sqlite!.prepare('UPDATE bot_session_links SET role=? WHERE session_id=?').run(role, created.session.id);+ const makeOpts = (): MakerSessionCreateOpts => ({+ id: created.session.id, agentKind: 'codex', workingDir: created.session.workingDir,+ workspaceKind: 'dialogue', model: 'gpt-5', permissionMode: 'bypassPermissions',+ });+ let index = '# Memory\n';+ let updatedAt = 'v1';+ const deps = {+ readMemoryIndex: async () => index,+ listOwnSkills: async () => ({ pluginRoot: '/skills', skills: [{+ name: 'report', description: 'A verified report format', path: '/skills/report', updatedAt,+ }] }),+ };+ const initial = await hydrateBotProfileRuntime(makeOpts(), deps);+ await markBotProfileRuntimeApplied(initial!);+ expect((await hydrateBotProfileRuntime(makeOpts(), deps))?.runtimeEpochChanged).toBe(false);+ index += '- [Conclusion first](feedback_conclusion.md)\n';+ const changed = await hydrateBotProfileRuntime(makeOpts(), deps);+ expect(changed?.runtimeEpochChanged).toBe(true);+ await markBotProfileRuntimeApplied(changed!);+ expect((await hydrateBotProfileRuntime(makeOpts(), deps))?.runtimeEpochChanged).toBe(false);+ updatedAt = 'v2';+ expect((await hydrateBotProfileRuntime(makeOpts(), deps))?.runtimeEpochChanged).toBe(true);+ } finally {+ clock.mockRestore();+ }});it('refreshes canonical Skill resources in place when their fingerprint changes', async () => {diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.tsindex 3874456b94..849ebf0b28 100644--- a/apps/desktop/src/main/localDb/ipc/bots.ts+++ b/apps/desktop/src/main/localDb/ipc/bots.ts@@ -98,6 +98,8 @@ import {isBotTemplatePresetId,} from '../../../shared/botTemplatePreset.js';import { createMessage } from './messages.js';+import { syncBotLanePermission, syncBotLinkedLanePermissions } from '../../maker-ipc/botPermissionSync.js';+import { withSessionPermissionChange } from '../../maker-ipc/sessionPermissionChange.js';import { broadcastSessionPatched } from './sessions.js';import { BOT_DELEGATION_CLIENT_ID } from '../../../shared/botCollaboration.js';@@ -347,7 +349,11 @@ export async function ensureBotGroupLaneSession(input: {eq(sessions.status, 'active'),)).limit(1);- if (existing) return { ok: true, sessionId: existing.sessionId, created: false };+ if (existing) {+ await syncBotLanePermission(existing.sessionId);+ owner.assertCurrent();+ return { ok: true, sessionId: existing.sessionId, created: false };+ }const [profile] = await db.select().from(botProfiles).where(eq(botProfiles.id, input.botId)).limit(1);if (!profile || profile.status !== 'active') {return { ok: false, errorCode: 'MEMBER_UNAVAILABLE', message: '伙伴当前不可用' };@@ -460,7 +466,11 @@ export async function ensureBotChannelLaneSession(input: {const client = getDbClient();const db = client.drizzle;const existing = await findBotChannelLaneSession(input.botId, input.routeKey);- if (existing) return { ok: true, sessionId: existing, created: false };+ if (existing) {+ await syncBotLanePermission(existing);+ owner.assertCurrent();+ return { ok: true, sessionId: existing, created: false };+ }const [profile] = await db.select().from(botProfiles).where(eq(botProfiles.id, input.botId)).limit(1);if (!profile || profile.status !== 'active') {return { ok: false, errorCode: 'BOT_UNAVAILABLE', message: '伙伴当前不可用' };@@ -575,7 +585,11 @@ export async function ensureBotDmThreadSession(input: {eq(sessions.status, 'active'),)).limit(1);- if (existing) return { ok: true, sessionId: existing.sessionId, created: false };+ if (existing) {+ await syncBotLanePermission(existing.sessionId);+ owner.assertCurrent();+ return { ok: true, sessionId: existing.sessionId, created: false };+ }const [profile] = await db.select().from(botProfiles).where(eq(botProfiles.id, input.botId)).limit(1);if (!profile || profile.status !== 'active') {return { ok: false, errorCode: 'BOT_UNAVAILABLE', message: '伙伴当前不可用' };@@ -1993,48 +2007,63 @@ export async function updateBotProfile(raw: unknown, expectedVersion?: number,owner.assertCurrent();const changesPermissions = body.capabilities != null && typeof body.capabilities === 'object'&& Object.prototype.hasOwnProperty.call(body.capabilities, 'permissions');- 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,- });- 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);+ const commitProfile = async () => {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.+ 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,+ });+ 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.+ owner.assertCurrent();+ if (maker?.getSession(canonical.sessionId) === live) await maker?.closeSession(canonical.sessionId);+ throw error;+ } finally {+ owner.assertCurrent();+ await syncBotLinkedLanePermissions(canonical.sessionId);+ }owner.assertCurrent();- if (maker?.getSession(canonical.sessionId) === live) await maker?.closeSession(canonical.sessionId);- throw error;+ broadcastSessionPatched(canonical.sessionId, { permissionMode: canonical.mode });}- 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.+ 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 --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 851e5a6eb8..a0bc118dae 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@@ -18,7 +18,7 @@ describe('Bot named worker transactions', () => {context_tokens INTEGER NOT NULL, context_window INTEGER NOT NULL, fast_mode INTEGER NOT NULL,plan_mode_enabled INTEGER NOT NULL, cleared_at INTEGER, pinned_at INTEGER, user_send_at INTEGER,agent_kind TEXT NOT NULL, orca_role TEXT, parent_session_id TEXT, forked_at_message_id TEXT,- worktree_path TEXT, extra_dirs TEXT NOT NULL, remote_host_id TEXT, provider_id TEXT,+ worktree_path TEXT, extra_dirs TEXT NOT NULL, remote_host_id TEXT, provider_id TEXT, agent_device_id TEXT,source TEXT NOT NULL, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);CREATE TABLE bot_profiles (@@ -130,6 +130,35 @@ describe('Bot named worker transactions', () => {).toEqual({ hiddenAt: null, pinnedAt: null });});+ // #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: {id: 'bot-1', displayName: 'Hermes', description: '', avatar: '🤖', avatarColor: 'violet',@@ -159,6 +188,46 @@ describe('Bot named worker transactions', () => {expect(db.prepare('SELECT COUNT(*) FROM sessions').pluck().get()).toBe(1);});+ // #6782: production named transactions must propagate a canonical choice in both+ // directions. Existing tests never changed permission after creating a channel.+ // Minimal failure: ask main + ask channel, save main bypass -> channel stayed ask.+ // Unit tier, isolated SQLite; this also covers new-lane snapshots and old-data repair.+ it('cascades canonical permissions without changing history or delegated work', () => {+ tx(db, { name: 'bots.createProfile', args: {+ id: 'bot-1', displayName: 'Hermes', description: '', avatar: '🤖', avatarColor: 'violet',+ identitySource: 'identity', capabilitiesJson: '{"permissions":"ask"}', now: 1,+ } });+ const session = (id: string) => ({ id, title: id, workingDir: '/tmp/fixture', workspaceKind: 'dialogue',+ model: 'm', effort: 'high', permissionMode: 'ask', agentKind: 'codex', extraDirs: '[]', source: 'bot', createdAt: 1, updatedAt: 1 });+ tx(db, { name: 'bots.replaceCanonicalSession', args: {+ botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1, session: session('main'), now: 1,+ } });+ tx(db, { name: 'bots.createChannelLane', args: { botId: 'bot-1', routeKey: 'im:feishu:g:1', session: session('feishu') } });+ for (const role of ['group', 'thread', 'delegation', 'history']) {+ db.prepare(`INSERT INTO sessions SELECT ?, title, working_dir, workspace_kind, model, effort, permission_mode, status,+ scheduled_model_baseline, sdk_session_id, total_token_usage, total_cost_usd, context_tokens, context_window, fast_mode,+ plan_mode_enabled, cleared_at, pinned_at, user_send_at, agent_kind, orca_role, parent_session_id, forked_at_message_id,+ worktree_path, extra_dirs, remote_host_id, provider_id, agent_device_id, source, created_at, updated_at FROM sessions WHERE id = 'main'`).run(role);+ db.prepare('INSERT INTO bot_session_links (id, bot_id, session_id, profile_version, role, created_at, archived_at) VALUES (?, ?, ?, 1, ?, 1, ?)')+ .run(role, 'bot-1', role, role, role === 'history' ? 1 : null);+ }+ const mode = (id: string) => db.prepare('SELECT permission_mode FROM sessions WHERE id = ?').pluck().get(id);+ for (const next of ['bypassPermissions', 'auto', 'ask']) {+ tx(db, { name: 'bots.persistSessionPermission', args: { sessionId: 'main', mode: next } });+ expect(['main', 'feishu', 'group', 'thread'].map(mode)).toEqual([next, next, next, next]);+ expect(['delegation', 'history'].map(mode)).toEqual(['ask', 'ask']);+ }+ // A stale preflight must not mint a lane with authority older than the Profile.+ tx(db, { name: 'bots.persistSessionPermission', args: { sessionId: 'main', mode: 'bypassPermissions' } });+ tx(db, { name: 'bots.createChannelLane', args: { botId: 'bot-1', routeKey: 'im:feishu:g:2', session: session('new') } });+ expect(mode('new')).toBe('bypassPermissions');+ db.prepare("UPDATE bot_profile_versions SET capabilities_json = ? WHERE bot_id = 'bot-1'").run(JSON.stringify({ permissions: 'ask' }));+ expect(tx(db, { name: 'bots.reconcileLanePermission', args: { sessionId: 'feishu' } })).toMatchObject({ mode: 'ask' });+ expect(mode('feishu')).toBe('ask');+ expect(tx(db, { name: 'bots.reconcileLanePermission', args: { sessionId: 'history' } })).toMatchObject({ mode: null });+ expect(db.prepare('SELECT COUNT(*) FROM sessions').pluck().get()).toBe(7);+ });+it('does not insert a losing canonical CAS session', () => {tx(db, { name: 'bots.createProfile', args: {id: 'bot-1', displayName: 'Hermes', description: '', avatar: '🤖', avatarColor: 'violet',diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex 0d8760aad5..b95f0aae2e 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@ -175,6 +175,8 @@ function dispatchTransaction(db: Database.Database, args: unknown): unknown {case 'bots.prepareProfileDeletion':expectString(asRecord(txArgs, 'args').botId, 'botId');return undefined;+ case 'bots.reconcileLanePermission':+ return botsReconcileLanePermission(db, txArgs);case 'bots.persistSessionPermission':return botsPersistSessionPermission(db, txArgs);case 'bots.createGroupLane':@@ -409,7 +411,33 @@ function botsUpdateProfile(db: Database.Database, args: unknown): { currentVersivalues.push(p[key] === null ? null : expectNumber(p[key], key));}}- const changed = p.profileContentChanged === true;+ const editsContent = p.profileContentChanged === true;+ const permissionMode = p.canonicalPermissionMode === undefined ? undefined+ : expectString(p.canonicalPermissionMode, 'canonicalPermissionMode');+ if (permissionMode !== undefined && !['ask', 'auto', 'bypassPermissions'].includes(permissionMode)) {+ throw new Error('Invalid canonical permission mode');+ }+ const latest = editsContent || permissionMode !== undefined+ ? db.prepare('SELECT capabilities_json AS json, identity_source AS identity FROM bot_profile_versions WHERE bot_id = ? AND version = ?')+ .get(id, expectedVersion) as { json: string; identity: string } | undefined+ : undefined;+ if ((editsContent || permissionMode !== undefined) && !latest) {+ throw Object.assign(new Error('Bot profile version missing'), { code: 'PRECONDITION_FAILED' });+ }+ const latestConfig = latest ? asRecord(JSON.parse(latest.json), 'capabilities') : undefined;+ const nextConfig = editsContent+ ? asRecord(JSON.parse(expectString(p.capabilitiesJson, 'capabilitiesJson')), 'capabilities')+ : latestConfig ? { ...latestConfig } : undefined;+ const permission = permissionMode === 'bypassPermissions' ? 'trusted' : permissionMode;+ if (nextConfig && latestConfig) {+ // Composer saves can change permissions in place without losing the version+ // CAS. Preserve that latest value unless this is an explicit permission edit.+ if (permission !== undefined) nextConfig.permissions = permission;+ else if (Object.prototype.hasOwnProperty.call(latestConfig, 'permissions')) nextConfig.permissions = latestConfig.permissions;+ else delete nextConfig.permissions;+ }+ // A same-value settings edit can become a real change while waiting to commit.+ const changed = editsContent || (permission !== undefined && latestConfig?.permissions !== permission);const nextVersion = changed ? expectedVersion + 1 : expectedVersion;if (changed) {fields.push('current_version = ?');@@ -434,8 +462,8 @@ function botsUpdateProfile(db: Database.Database, args: unknown): { currentVersidb.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);+ .run(`${id}:v${nextVersion}`, id, nextVersion, p.identitySource === undefined ? latest!.identity : expectString(p.identitySource, 'identitySource'),+ JSON.stringify(nextConfig), now);// 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@@ -444,9 +472,8 @@ function botsUpdateProfile(db: Database.Database, args: unknown): { currentVersiWHERE bot_id = ? AND role IN ('canonical', 'group', 'channel', 'thread') AND archived_at IS NULL`).run(nextVersion, 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 IN@@ -807,6 +834,7 @@ function botsCreateGroupLane(db: Database.Database, args: BotGroupsCreateLaneArg(id, bot_id, session_id, profile_version, role, route_key, created_at, archived_at)VALUES (?, ?, ?, ?, 'group', ?, ?, NULL)`).run(`${botId}:${sessionId}`, botId, sessionId, profile.version, routeKey, createdAt);+ botsReconcileLanePermission(db, { sessionId });return { sessionId, created: true };})();}@@ -842,6 +870,7 @@ function botsCreateChannelLane(db: Database.Database, args: BotsCreateChannelLan(id, bot_id, session_id, profile_version, role, route_key, created_at, archived_at)VALUES (?, ?, ?, ?, 'channel', ?, ?, NULL)`).run(`${botId}:${sessionId}`, botId, sessionId, profile.version, routeKey, createdAt);+ botsReconcileLanePermission(db, { sessionId });return { sessionId, created: true };})();}@@ -886,6 +915,7 @@ function botsCreateThreadLane(db: Database.Database, args: BotsCreateThreadLaneA(id, bot_id, session_id, profile_version, role, route_key, created_at, archived_at)VALUES (?, ?, ?, ?, 'thread', ?, ?, NULL)`).run(`${botId}:${sessionId}`, botId, sessionId, profile.version, routeKey, createdAt);+ botsReconcileLanePermission(db, { sessionId });return { sessionId, created: true };})();}@@ -1259,12 +1289,44 @@ function botsPersistSessionPermission(}}}- db.prepare('UPDATE sessions SET permission_mode = ?, updated_at = ? WHERE id = ?')- .run(mode, Date.now(), sessionId);+ if (link) {+ db.prepare(`UPDATE sessions SET permission_mode = ?, updated_at = ? WHERE source = 'bot' AND status = 'active' AND 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(mode, Date.now(), link.botId);+ } else {+ db.prepare('UPDATE sessions SET permission_mode = ?, updated_at = ? WHERE id = ?')+ .run(mode, Date.now(), sessionId);+ }return { updated: true };})();}+/** Repair old lane snapshots from the active Profile, never from the widest stored value. */+function botsReconcileLanePermission(db: Database.Database, args: unknown): { mode: string | null; changed: boolean } {+ const sessionId = expectString(asRecord(args, 'args').sessionId, 'sessionId');+ return db.transaction(() => {+ const row = db.prepare(`SELECT v.capabilities_json AS json FROM bot_session_links l+ JOIN sessions s ON s.id = l.session_id+ JOIN bot_profiles p ON p.id = l.bot_id+ LEFT JOIN bot_profile_versions v ON v.bot_id = p.id AND v.version = p.current_version+ WHERE l.session_id = ? AND l.role IN ('channel', 'group', 'thread') AND l.archived_at IS NULL+ AND s.source = 'bot' AND s.status = 'active' AND p.status = 'active'`).get(sessionId) as { json: string | null } | undefined;+ if (!row) return { mode: null, changed: false };+ let parsed: unknown;+ try { parsed = typeof row.json === 'string' ? JSON.parse(row.json) : null; }+ catch { parsed = null; }+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {+ throw Object.assign(new Error('Bot profile capabilities are unreadable'), { code: 'PRECONDITION_FAILED' });+ }+ const config = parsed as Record<string, unknown>;+ const mode = config.permissions === 'trusted' ? 'bypassPermissions' : config.permissions === 'auto' ? 'auto' : 'ask';+ const changed = db.prepare('UPDATE sessions SET permission_mode = ?, updated_at = ? WHERE id = ? AND permission_mode != ?')+ .run(mode, Date.now(), sessionId, mode).changes > 0;+ return { mode, changed };+ })();+}+function detachSharedHistoryForProfileDeletion(db: Database.Database, botId: string): void {const delegationColumns = tableColumns(db, 'bot_delegations');if (delegationColumns.has('target_bot_id')) {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botGroupLaneTx.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botGroupLaneTx.test.tsindex 370838ea76..e71d922568 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botGroupLaneTx.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botGroupLaneTx.test.ts@@ -54,6 +54,8 @@ describe('Bot group lane transactions', () => {status TEXT NOT NULL,current_version INTEGER NOT NULL DEFAULT 1);+ CREATE TABLE bot_profile_versions (bot_id TEXT, version INTEGER, capabilities_json TEXT);+ INSERT INTO bot_profile_versions VALUES ('mimi',3,'{"permissions":"ask"}'), ('abu',1,'{"permissions":"ask"}');CREATE TABLE sessions (id TEXT PRIMARY KEY, title TEXT, working_dir TEXT, workspace_kind TEXT, model TEXT,scheduled_model_baseline TEXT,diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botReleasedHostCompatibility.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botReleasedHostCompatibility.test.tsindex 6e6f122cdb..2b41a16657 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botReleasedHostCompatibility.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botReleasedHostCompatibility.test.ts@@ -113,7 +113,7 @@ function oldHost() {}).createMakerSendTransaction(deps);const guardedSend = released('sendToAgentAccepted', {}, {sendToAgentAcceptedUnlocked: transaction.sendToAgentAccepted,- assertReviewExternalInputAllowed: async () => {}, reconcileBotModelRoute: async () => {},+ syncBotLanePermission: async () => {}, assertReviewExternalInputAllowed: async () => {}, reconcileBotModelRoute: async () => {},maker: { getSession: () => engine }, refreshBotCapabilityEpochBeforeSend: async () => {},withSendToSessionLock: async (_id: string, run: () => unknown) => run(),getDbClient: () => ({ drizzle: db }), sessions, botProfiles, botSessionLinks, eq: orm.eq,diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.tsindex 53af65d30b..b38397c41f 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts@@ -46,7 +46,7 @@ function fixture() {let remote = false;const persistedResults = new WeakSet<object>();const forgetGrants = vi.fn();- const settingDeps = {...deps, forgetCredentialGrants:forgetGrants, log:{warn:vi.fn()}, ipcMain:{handle:(_name:unknown,fn:typeof setMode)=>{setMode=fn;}}, MAKER_INVOKE:{SET_PERMISSION_MODE:'permission'}, isDeviceLinkInvoke:()=>remote, assertTrustedAppRendererEvent:()=>{}, assertReviewSettingsUnlocked:async()=>{}, isSessionPermissionMode:()=>true, throwIpcError:(code:string,message:string)=>{throw Object.assign(Error(message),{code});}, persistPermissionModeWithoutRuntime:async(_id:string,mode:string)=>(await epoch.client.tx('bots.persistSessionPermission',{mode})).updated, markRemoteSettingPersistedInsideHandler:(result:object)=>persistedResults.add(result)};+ const settingDeps = {...deps, syncBotLinkedLanePermissions: vi.fn(async()=>{}), forgetCredentialGrants:forgetGrants, log:{warn:vi.fn()}, ipcMain:{handle:(_name:unknown,fn:typeof setMode)=>{setMode=fn;}}, MAKER_INVOKE:{SET_PERMISSION_MODE:'permission'}, isDeviceLinkInvoke:()=>remote, assertTrustedAppRendererEvent:()=>{}, assertReviewSettingsUnlocked:async()=>{}, isSessionPermissionMode:()=>true, throwIpcError:(code:string,message:string)=>{throw Object.assign(Error(message),{code});}, persistPermissionModeWithoutRuntime:async(_id:string,mode:string)=>(await epoch.client.tx('bots.persistSessionPermission',{mode})).updated, markRemoteSettingPersistedInsideHandler:(result:object)=>persistedResults.add(result)};new Function(...Object.keys(settingDeps), settingJs)(...Object.values(settingDeps));expect(setMode, 'SET_PERMISSION_MODE source extraction must register its handler').toBeTypeOf('function');const planPersist=vi.fn(async(_id:string,patch:{planModeEnabled:boolean})=>{history.planModeEnabled=patch.planModeEnabled;});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.tsindex ca5fb023b9..f9dd4e6f87 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.ts@@ -181,6 +181,7 @@ function botTaskDispatchHarness(sessionQueueOriginForDispatcher: noop,extractPlainText: (value: unknown) => String(value ?? ''),assertReviewExternalInputAllowed: asyncNoop,+ syncBotLanePermission: asyncNoop,reconcileBotModelRoute: asyncNoop,refreshBotCapabilityEpochBeforeSend: asyncNoop,assertSessionNotRestarting: noop,diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionPermissionPersistence.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionPermissionPersistence.test.tsindex 5ede4fcd77..b669520937 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionPermissionPersistence.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionPermissionPersistence.test.ts@@ -1,17 +1,27 @@import Database from 'better-sqlite3';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { tx as runWorkerTx } from '../../localDb/worker/opHandlers/tx.js';const h = vi.hoisted(() => ({sqlite: null as Database.Database | null,+ owner: null as object | null,+ live: new Map<string, { stablePermissionModeState: {mode: string}; setPermissionMode: ReturnType<typeof vi.fn> }>(),+ patched: vi.fn(),+ close: vi.fn(),+ forget: vi.fn(),}));+vi.mock('../../maker-host/index.js', () => ({ getMakerIfReady: () => ({ getSession: (id: string) => h.live.get(id), closeSession: h.close }) }));+vi.mock('../../localDb/ipc/sessions.js', () => ({ broadcastSessionPatched: h.patched }));+vi.mock('../../remote-agent/executor/credentialGrants.js', () => ({ forgetCredentialGrants: h.forget }));vi.mock('../../localDb/client/current.js', () => ({+ getCurrentDbClientSnapshot: () => h.owner,getDbClient: () => ({tx: (name: string, args: unknown) => runWorkerTx(h.sqlite!, { name, args } as never),}),}));+import { syncBotLanePermission, syncBotLinkedLanePermissions } from '../botPermissionSync.js';import { persistPermissionModeWithoutRuntime, profilePermissionForSessionMode } from '../sessionPermissionPersistence.js';function createDatabase(): Database.Database {@@ -20,11 +30,11 @@ function createDatabase(): Database.Database {CREATE TABLE sessions (id TEXT PRIMARY KEY,permission_mode TEXT NOT NULL,- updated_at INTEGER NOT NULL+ updated_at INTEGER NOT NULL, source TEXT DEFAULT 'bot', status TEXT DEFAULT 'active');CREATE TABLE bot_profiles (id TEXT PRIMARY KEY,- current_version INTEGER NOT NULL+ current_version INTEGER NOT NULL, status TEXT DEFAULT 'active');CREATE TABLE bot_session_links (bot_id TEXT NOT NULL,@@ -37,8 +47,8 @@ function createDatabase(): Database.Database {version INTEGER NOT NULL,capabilities_json TEXT NOT NULL);- INSERT INTO sessions VALUES ('chat', 'ask', 1);- INSERT INTO bot_profiles VALUES ('bot-1', 2);+ INSERT INTO sessions (id, permission_mode, updated_at) VALUES ('chat', 'ask', 1);+ INSERT INTO bot_profiles (id, current_version) VALUES ('bot-1', 2);INSERT INTO bot_session_links VALUES ('bot-1', 'chat', 'canonical', NULL);INSERT INTO bot_profile_versions VALUES ('bot-1', 2, '{"permissions":"ask","memory":true}');`);@@ -51,8 +61,17 @@ describe('permission persistence without a live runtime', () => {beforeEach(() => {sqlite = createDatabase();h.sqlite = sqlite;+ h.live.clear(); h.patched.mockClear(); h.forget.mockClear();+ h.close.mockReset().mockImplementation(async (id: string) => { h.live.delete(id); });+ h.owner = { client: {+ tx: async (name: string, args: unknown) => runWorkerTx(sqlite, {name, args} as never),+ query: async (sql: string, params: unknown[]) => sqlite.prepare(sql).all(...params),+ } };+});+ afterEach(() => { sqlite.close(); h.owner = null; });+it('maps only the teammate permission values', () => {expect(profilePermissionForSessionMode('bypassPermissions')).toBe('trusted');expect(profilePermissionForSessionMode('acceptEdits')).toBeNull();@@ -79,4 +98,69 @@ describe('permission persistence without a live runtime', () => {expect(JSON.parse(sqlite.prepare('SELECT capabilities_json FROM bot_profile_versions WHERE version = 2').pluck().get() as string)).toEqual({ permissions: 'ask', memory: true });});+ // #6782, unit: real persistence transactions + runtime adapter. Earlier coverage+ // checked only the main row, so live channels could retain a wider permission.+ // Minimal failure: stored Profile ask, already running channel bypass.+ it('repairs and hot-switches every linked lane while preserving other Bots', async () => {+ sqlite.exec(`INSERT INTO sessions (id, permission_mode, updated_at) VALUES ('lane','bypassPermissions',1), ('other','bypassPermissions',1);+ INSERT INTO bot_session_links VALUES ('bot-1','lane','channel',NULL), ('bot-2','other','channel',NULL);`);+ const live = { stablePermissionModeState: { mode: 'bypassPermissions' }, setPermissionMode: vi.fn(async (mode: string) => { live.stablePermissionModeState = {mode}; }) };+ h.live.set('lane', live);+ await syncBotLinkedLanePermissions('chat');+ expect(live.stablePermissionModeState.mode).toBe('ask');+ expect(sqlite.prepare("SELECT permission_mode FROM sessions WHERE id = 'lane'").pluck().get()).toBe('ask');+ expect(sqlite.prepare("SELECT permission_mode FROM sessions WHERE id = 'other'").pluck().get()).toBe('bypassPermissions');+ expect(h.patched).toHaveBeenCalledWith('lane', {permissionMode:'ask'});+ await persistPermissionModeWithoutRuntime('chat', 'bypassPermissions');+ await syncBotLinkedLanePermissions('chat');+ expect(live.stablePermissionModeState.mode).toBe('bypassPermissions');+ h.live.delete('lane');+ await persistPermissionModeWithoutRuntime('chat', 'auto');+ await syncBotLanePermission('lane');+ expect(sqlite.prepare("SELECT permission_mode FROM sessions WHERE id = 'lane'").pluck().get()).toBe('auto');+ });++ it('closes a stale runtime when tightening fails and still synchronizes other lanes', async () => {+ sqlite.exec(`INSERT INTO sessions (id, permission_mode, updated_at) VALUES ('bad','bypassPermissions',1), ('good','bypassPermissions',1);+ INSERT INTO bot_session_links VALUES ('bot-1','bad','channel',NULL), ('bot-1','good','channel',NULL);`);+ const good = { stablePermissionModeState: { mode: 'bypassPermissions' }, setPermissionMode: vi.fn(async (mode: string) => { good.stablePermissionModeState = {mode}; }) };+ h.live.set('bad', { stablePermissionModeState: { mode: 'bypassPermissions' }, setPermissionMode: vi.fn(async () => { throw new Error('switch failed'); }) });+ h.live.set('good', good);+ await expect(syncBotLinkedLanePermissions('chat')).rejects.toThrow('switch failed');+ expect(h.live.has('bad')).toBe(false);+ expect(good.stablePermissionModeState.mode).toBe('ask');+ });++ it('serializes successive lane updates and discards an outgoing account continuation', async () => {+ sqlite.exec(`INSERT INTO sessions (id, permission_mode, updated_at) VALUES ('lane','bypassPermissions',1);+ INSERT INTO bot_session_links VALUES ('bot-1','lane','channel',NULL);`);+ let release!: () => void;+ let entered!: () => void;+ const started = new Promise<void>(resolve => { entered = resolve; });+ const pending = new Promise<void>(resolve => { release = resolve; });+ const live = { stablePermissionModeState: { mode: 'bypassPermissions' }, setPermissionMode: vi.fn(async (mode: string) => { entered(); await pending; live.stablePermissionModeState = {mode}; }) };+ h.live.set('lane', live);+ const first = syncBotLanePermission('lane'); await started;+ runWorkerTx(sqlite, {name: 'bots.persistSessionPermission', args: {sessionId: 'chat', mode: 'auto'}});+ const second = syncBotLanePermission('lane'); release();+ await Promise.all([first, second]);+ expect(live.stablePermissionModeState.mode).toBe('auto');+ h.patched.mockClear();+ const owner = h.owner as {client: {tx: unknown}};+ owner.client.tx = async () => { h.owner = {}; return {mode:'ask'}; };+ await expect(syncBotLanePermission('lane')).rejects.toThrow('Account changed');+ expect(h.patched).not.toHaveBeenCalled();+ });++ it.each(['missing', 'malformed'])('does not keep old authority when the active Profile is %s', async failure => {+ sqlite.exec(`INSERT INTO sessions (id, permission_mode, updated_at) VALUES ('lane','bypassPermissions',1);+ INSERT INTO bot_session_links VALUES ('bot-1','lane','channel',NULL);`);+ if (failure === 'missing') sqlite.exec('DELETE FROM bot_profile_versions');+ else sqlite.exec("UPDATE bot_profile_versions SET capabilities_json = 'null'");+ h.live.set('lane', {stablePermissionModeState:{mode:'bypassPermissions'},setPermissionMode:vi.fn()});+ await expect(syncBotLanePermission('lane')).rejects.toThrow('unreadable');+ expect(h.live.has('lane')).toBe(false);+ expect(sqlite.prepare('SELECT COUNT(*) FROM sessions').pluck().get()).toBe(2);+ });+});diff --git a/apps/desktop/src/main/maker-ipc/botPermissionSync.ts b/apps/desktop/src/main/maker-ipc/botPermissionSync.tsnew file mode 100644index 0000000000..26a537a313--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/botPermissionSync.ts@@ -0,0 +1,63 @@+import type { PermissionMode } from '@cindy/maker-core';+import { getCurrentDbClientSnapshot } from '../localDb/client/current.js';+import { broadcastSessionPatched } from '../localDb/ipc/sessions.js';+import { getMakerIfReady } from '../maker-host/index.js';+import { forgetCredentialGrants } from '../remote-agent/executor/credentialGrants.js';+import { withSessionPermissionChange } from './sessionPermissionChange.js';++/** Follow committed values under the same fence as explicit permission changes. */+export async function syncBotLanePermission(sessionId: string): Promise<void> {+ const owner = getCurrentDbClientSnapshot();+ if (!owner) return;+ await withSessionPermissionChange(sessionId, async () => {+ const assertCurrent = () => {+ if (getCurrentDbClientSnapshot() !== owner) throw new Error('Account changed during lane permission update');+ };+ assertCurrent();+ let saved: { mode: string | null; changed: boolean };+ try {+ saved = await owner.client.tx('bots.reconcileLanePermission', { sessionId });+ } catch (error) {+ assertCurrent();+ const maker = getMakerIfReady();+ if (maker?.getSession(sessionId)) await maker.closeSession(sessionId);+ throw error;+ }+ const { mode, changed } = saved;+ assertCurrent();+ if (!mode) return;+ const maker = getMakerIfReady();+ const live = maker?.getSession(sessionId);+ if (changed || (live && live.stablePermissionModeState?.mode !== mode)) forgetCredentialGrants(sessionId);+ if (live && live.stablePermissionModeState?.mode !== mode) {+ try {+ await live.setPermissionMode(mode as PermissionMode);+ } catch (error) {+ assertCurrent();+ // Never leave a failed tightening running with its previous authority.+ if (maker?.getSession(sessionId) === live) await maker.closeSession(sessionId);+ throw error;+ }+ assertCurrent();+ }+ broadcastSessionPatched(sessionId, { permissionMode: mode });+ });+}++/** Called after a canonical save; delegated work and archived history keep their own authority. */+export async function syncBotLinkedLanePermissions(canonicalSessionId: string): Promise<void> {+ const owner = getCurrentDbClientSnapshot();+ if (!owner) return;+ const rows = await owner.client.query<{ sessionId: string }>(`SELECT l.session_id AS sessionId+ FROM bot_session_links l JOIN bot_session_links c ON c.bot_id = l.bot_id+ WHERE c.session_id = ? AND c.role = 'canonical' AND c.archived_at IS NULL+ AND l.role IN ('channel', 'group', 'thread') AND l.archived_at IS NULL`, [canonicalSessionId]);+ if (getCurrentDbClientSnapshot() !== owner) throw new Error('Account changed during lane permission update');+ // Settle every lane even if one fails, so a failure cannot strand another old runtime.+ const results = await Promise.allSettled(rows.map(row => {+ forgetCredentialGrants(row.sessionId);+ return syncBotLanePermission(row.sessionId);+ }));+ const failed = results.find(result => result.status === 'rejected');+ if (failed?.status === 'rejected') throw failed.reason;+}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 74622fc950..883efea223 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -623,6 +623,7 @@ import { requestUtilityText } from '../utility-model/oneShotCandidates.js';import { validateExistingLocalProjectDirectory } from '../mcp-integrations/createProject.js';import { gitExec } from '../worktree/gitExec.js';import { BOT_GROUP_CLIENT_ID_PREFIX } from '../../shared/botGroupChat.js';+import { syncBotLanePermission, syncBotLinkedLanePermissions } from './botPermissionSync.js';import { ensureBotGroupLaneSession } from '../localDb/ipc/bots.js';import { restartBotRuntime } from './botRuntimeRestart.js';import { registerBotLifecycleHandlers } from './botLifecycleService.js';@@ -11450,6 +11451,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)message: error instanceof Error ? error.message : String(error),};}+ await syncBotLanePermission(targetSessionId);await reconcileBotModelRoute(targetSessionId);const compactedRuntime = maker.getSession(targetSessionId);if (compactedRuntime) await refreshBotCapabilityEpochBeforeSend(compactedRuntime);@@ -12530,26 +12532,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)closeLanes: async (sessionIds) => {await Promise.all(sessionIds.map((id) => maker.closeSession(id).catch(() => undefined)));},- syncLanePermission: async (laneSessionId, botId) => {- const [canonical] = await getDbClient().drizzle- .select({ mode: sessions.permissionMode })- .from(botSessionLinks)- .innerJoin(sessions, eq(sessions.id, botSessionLinks.sessionId))- .where(and(eq(botSessionLinks.botId, botId), eq(botSessionLinks.role, 'canonical'), isNull(botSessionLinks.archivedAt)))- .limit(1);- const mode = canonical?.mode;- if (!mode || !isSessionPermissionMode(mode)) return;- const live = maker.getSession(laneSessionId);- if (live) {- if (live.stablePermissionModeState?.mode !== mode) {- await live.setPermissionMode(mode as 'ask' | 'default' | 'acceptEdits' | 'plan' | 'auto' | 'bypassPermissions');- }- return;- }- if (!(await persistPermissionModeWithoutRuntime(laneSessionId, mode))) {- throw new Error('Group lane permission could not be persisted');- }- },+ syncLanePermission: async (laneSessionId) => syncBotLanePermission(laneSessionId),hasPendingInteraction: (sessionId) => hasPendingAgentInteractionForSession(sessionId),decidePlan: createBotGroupPlanDecider((prompt, opts) => requestUtilityText(maker, prompt, opts)),workDir: botGroupWorkDir,@@ -17533,6 +17516,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)throwIpcError('PRECONDITION_FAILED', 'Cindy Make is still preparing this task');}await assertReviewExternalInputAllowed(sessionId);+ await syncBotLanePermission(sessionId);await reconcileBotModelRoute(sessionId);const compactedRuntime = maker.getSession(sessionId);if (compactedRuntime) await refreshBotCapabilityEpochBeforeSend(compactedRuntime);@@ -17601,6 +17585,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// TODO(im-bot-companion): IM turns do not yet get the desktop model-chain// fallback (botFallbackInputs / coordinator recovery); a failing primary// route surfaces as an IM error instead of moving to the next candidate.+ await syncBotLanePermission(sessionId);await reconcileBotModelRoute(sessionId);const live = maker.getSession(sessionId);if (live) await refreshBotCapabilityEpochBeforeSend(live);@@ -23554,6 +23539,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 分享供应商的「本任务总是允许」随权限档变化失效;Agent 实例被回收时执行器收不到这次切换。if (row.permissionMode !== mode) forgetCredentialGrants(sessionId);broadcastSessionPatched(sessionId, { permissionMode: mode });+ await syncBotLinkedLanePermissions(sessionId);if (remote) {const result = {};markRemoteSettingPersistedInsideHandler(result);diff --git a/apps/desktop/src/main/maker-ipc/sessionPermissionPersistence.ts b/apps/desktop/src/main/maker-ipc/sessionPermissionPersistence.tsindex 89e30eb774..21aed6b703 100644--- a/apps/desktop/src/main/maker-ipc/sessionPermissionPersistence.ts+++ b/apps/desktop/src/main/maker-ipc/sessionPermissionPersistence.ts@@ -1,4 +1,5 @@-import { getDbClient } from '../localDb/client/current.js';+import { syncBotLinkedLanePermissions } from './botPermissionSync.js';+import { getCurrentDbClientSnapshot } from '../localDb/client/current.js';const SESSION_PERMISSION_MODES = new Set(['ask',@@ -30,6 +31,10 @@ export async function persistPermissionModeWithoutRuntime(mode: string,): Promise<boolean> {if (!isSessionPermissionMode(mode)) return false;- const saved = await getDbClient().tx('bots.persistSessionPermission', { sessionId, mode });+ const owner = getCurrentDbClientSnapshot();+ if (!owner) throw new Error('DbClient not ready');+ const saved = await owner.client.tx('bots.persistSessionPermission', { sessionId, mode });+ if (getCurrentDbClientSnapshot() !== owner) throw new Error('Account changed during permission update');+ if (saved.updated) await syncBotLinkedLanePermissions(sessionId);return saved.updated;}diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex fc7269e77e..a5a3353fc7 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -129,6 +129,16 @@ Telegram 设为全响应的群;设置页的人格与行为配置不带。移伙伴设为「完全访问」时三种 Agent 都无法兑现逐轮策略,成员触发的轮次同样按完全访问直接执行而不是被拒跑——要成员动手前必须确认,把伙伴设成 Auto 或 Ask。连接不扩大任何权限。同一伙伴所有渠道共享记忆,不设每群记忆隔离。伙伴被删除时连接一并停掉、清凭证、归档专线。连接记录是账号级设置(`bot-im-connections.json`),不含凭证。+主任务显式切换 Ask / Auto / 完全访问时,当前 Profile 与有效的群、渠道、私聊话题专线+在同一事务保存权限;已有运行实例随后热切换并广播,失败的实例关闭,不能继续使用旧的宽权限。+普通模型、身份与资料保存保留事务提交时的最新权限,只有显式权限编辑才能替换它;+较早读取的 Profile 快照不能在稍后保存时撤销主人刚完成的权限提升或收紧。+设置页与主任务显式切档共用包含数据库与运行态的完整提交顺序;即使保存界面当前显示的+同一档位,也按提交时的最新 Profile 对齐,不能因早读快照看似未变而漏写权限。+存量专线在复用与发送前从当前 Profile 恢复,历史与委派任务不批量改档,也不删消息。+若历史主任务与 Profile 已分歧,不能推断哪次选择更新:专线以 Profile 为准,不取最宽值;+用户在主任务重新选择所需权限后,主任务、Profile 与专线重新对齐。实现与回归见+`maker-ipc/botPermissionSync.ts`、`sessionPermissionPersistence.test.ts` 与 `botTx.test.ts`。渠道行为:表情、回复引用档位用默认值,不读 设置 → IM 机器人 的人格与行为配置(伙伴的身份与分寸来自 SOUL);群参与模式(仅 @ / 全响应)按连接各一份,存在连接记录里,由「消息平台」页每条 Telegram 连接下的「群聊」小节设置(2026-10-17 补齐,全响应是能力不是分寸)。全响应群里每条未被召唤的消息先由 Cindy 的辅助模型链判一次