Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(bots): fence permission changes at provider dispatch

xuzini-xznd6feb24b1e3e
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
index 7c668b210e..ab79944386 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
@@ -992,6 +992,21 @@ describe('Bot canonical Session lifecycle', () => {
expect((await invoke('local-db:bots:get', 'bot-1')).capabilities.permissions).toBe('trusted');
});
+ // P1 review: settings remain available when the canonical task/link is absent.
+ // Persisted rows alone never updated an already loaded IM runtime in this case.
+ it('tightens a live channel from settings without a canonical link', async () => {
+ await invoke('local-db:bots:update', { id: 'bot-1', capabilities: { permissions: 'trusted' } });
+ const lane = await ensureBotChannelLaneSession({ botId: 'bot-1', routeKey: 'im:feishu:fixture:g:orphan', title: 'Orphan' });
+ if (!lane.ok) throw new Error(lane.message);
+ const live = { compactSession: vi.fn(), stablePermissionModeState: { mode: 'bypassPermissions' },
+ setPermissionMode: vi.fn(async (mode: string) => { live.stablePermissionModeState = { mode }; }) };
+ h.getSession.mockImplementation(id => id === lane.sessionId ? live : null);
+ await invoke('local-db:bots:update', { id: 'bot-1', capabilities: { permissions: 'ask' } });
+ expect(live.stablePermissionModeState.mode).toBe('ask');
+ expect(live.setPermissionMode).toHaveBeenCalledWith('ask');
+ expect(h.sqlite!.prepare('SELECT permission_mode FROM sessions WHERE id = ?').pluck().get(lane.sessionId)).toBe('ask');
+ });
+
// #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 () => {
diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.ts
index 56fd6b1533..e76f92da11 100644
--- a/apps/desktop/src/main/localDb/ipc/bots.ts
+++ b/apps/desktop/src/main/localDb/ipc/bots.ts
@@ -98,8 +98,9 @@ import {
isBotTemplatePresetId,
} from '../../../shared/botTemplatePreset.js';
import { createMessage } from './messages.js';
-import { syncBotLanePermission, syncBotLinkedLanePermissions } from '../../maker-ipc/botPermissionSync.js';
+import { syncBotLanePermission, syncBotLinkedLanePermissions, syncBotPermissionsByBotId } from '../../maker-ipc/botPermissionSync.js';
import { withSessionPermissionChange } from '../../maker-ipc/sessionPermissionChange.js';
+import { withBotPermissionChangeForBot } from '../../maker-ipc/botPermissionDispatch.js';
import { broadcastSessionPatched } from './sessions.js';
import { BOT_DELEGATION_CLIENT_ID } from '../../../shared/botCollaboration.js';
@@ -2049,21 +2050,23 @@ export async function updateBotProfile(raw: unknown, expectedVersion?: number,
.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 {
+ 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();
- await syncBotLinkedLanePermissions(canonical.sessionId);
+ broadcastSessionPatched(canonical.sessionId, { permissionMode: canonical.mode });
}
+ } finally {
owner.assertCurrent();
- broadcastSessionPatched(canonical.sessionId, { permissionMode: canonical.mode });
+ await syncBotPermissionsByBotId(id, canonical?.sessionId);
}
}
};
@@ -2073,8 +2076,10 @@ export async function updateBotProfile(raw: unknown, expectedVersion?: number,
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();
+ 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
diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
index 156df7182f..afd402d826 100644
--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
@@ -1264,7 +1264,8 @@ function botsPersistSessionPermission(
return { updated: true };
}
const link = db.prepare(`SELECT bot_id AS botId FROM bot_session_links
- WHERE session_id = ? AND role = 'canonical' AND archived_at IS NULL`).get(sessionId) as { botId: string } | undefined;
+ WHERE session_id = ? AND role IN ('canonical', 'channel', 'group', 'thread')
+ AND archived_at IS NULL`).get(sessionId) as { botId: string } | undefined;
if (link) {
const profile = db.prepare('SELECT current_version AS version FROM bot_profiles WHERE id = ?')
.get(link.botId) as { version: number } | undefined;
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts
index b38397c41f..a918ff4229 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts
@@ -38,7 +38,7 @@ function fixture() {
const slots = new Set<string>();
const dialog = { showMessageBox: vi.fn(async () => ({ response: 0 })) };
const write = vi.fn((_id: string, value: Record<string, unknown>) => { cfg = value; });
- const deps = { isPluginTaskPermissionAllowed, withSessionPermissionChange, withSessionRestartLock, drainPersistQueue:drain,messages,sessions,eq:()=>true,and:()=>true,service, getCurrentDbClientSnapshot: () => ownership.current, readPluginTaskConfig: () => cfg, pluginPermissionRequests: slots, PluginTaskError, maker: { getSession: () => cold ? null : live }, inputCoordinator: queue, dialog, t: (x: string) => x, getInstalledGhostName: () => 'fixture', clampPluginTaskPermissionMode: (x: string) => x, writePluginTaskConfig: write, broadcastSessionPatched: vi.fn() };
+ const deps = { isPluginTaskPermissionAllowed, withBotPermissionChange: async (_id: string, change: () => Promise<unknown>) => change(), withSessionPermissionChange, withSessionRestartLock, drainPersistQueue:drain,messages,sessions,eq:()=>true,and:()=>true,service, getCurrentDbClientSnapshot: () => ownership.current, readPluginTaskConfig: () => cfg, pluginPermissionRequests: slots, PluginTaskError, maker: { getSession: () => cold ? null : live }, inputCoordinator: queue, dialog, t: (x: string) => x, getInstalledGhostName: () => 'fixture', clampPluginTaskPermissionMode: (x: string) => x, writePluginTaskConfig: write, broadcastSessionPatched: vi.fn() };
const allDeps = {...deps, pluginWriteAccessGate:gate, pluginWriteAccessIdentity:()=>identity};
const run = new Function(...Object.keys(allDeps), js)(...Object.values(allDeps));
let setMode!: (event: unknown, sessionId: string, mode: string) => Promise<unknown>;
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionPermissionPersistence.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionPermissionPersistence.test.ts
index 85b6c97251..13b0bf7795 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionPermissionPersistence.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionPermissionPersistence.test.ts
@@ -23,6 +23,8 @@ vi.mock('../../localDb/client/current.js', () => ({
import { syncBotLanePermission, syncBotLinkedLanePermissions } from '../botPermissionSync.js';
import { persistPermissionModeWithoutRuntime, profilePermissionForSessionMode } from '../sessionPermissionPersistence.js';
+import { prepareBotPermissionDispatch, withBotPermissionChangeForBot } from '../botPermissionDispatch.js';
+import type { Session } from '@cindy/maker-core';
function createDatabase(): Database.Database {
const sqlite = new Database(':memory:');
@@ -89,6 +91,83 @@ describe('permission persistence without a live runtime', () => {
expect(sqlite.prepare('SELECT permission_mode FROM sessions').pluck().get()).toBe('ask');
});
+ // P1 review: a topic's explicit Ask choice previously changed only that row,
+ // then pre-send reconciliation restored the canonical's wider authority.
+ it.each(['thread', 'channel', 'group'])('persists explicit %s permission for the whole Bot', async role => {
+ await persistPermissionModeWithoutRuntime('chat', 'bypassPermissions');
+ sqlite.prepare("INSERT INTO sessions (id,permission_mode,updated_at) VALUES ('lane','bypassPermissions',1)").run();
+ sqlite.prepare("INSERT INTO bot_session_links VALUES ('bot-1','lane',?,NULL)").run(role);
+ await persistPermissionModeWithoutRuntime('lane', 'ask');
+ await syncBotLanePermission('lane');
+ expect(sqlite.prepare('SELECT DISTINCT permission_mode FROM sessions').pluck().all()).toEqual(['ask']);
+ expect(JSON.parse(sqlite.prepare('SELECT capabilities_json FROM bot_profile_versions').pluck().get() as string).permissions).toBe('ask');
+ });
+
+ // P1 review, unit: pause at the real async-preparation/synchronous-dispatch
+ // boundary. A persisted tightening must invalidate a previously prepared turn,
+ // including the interval before the lane's hot switch starts.
+ it.each(['pending', 'completed'])('rejects stale dispatch after a %s Bot permission change', async phase => {
+ await persistPermissionModeWithoutRuntime('chat', 'bypassPermissions');
+ const state = { id: 'chat', stablePermissionModeState: { mode: 'bypassPermissions' } };
+ const runtime = state as unknown as Session;
+ const dispatch = await prepareBotPermissionDispatch(runtime);
+ expect(() => dispatch()).not.toThrow();
+ let release!: () => void;
+ let entered!: () => void;
+ const pending = new Promise<void>(resolve => { release = resolve; });
+ const started = new Promise<void>(resolve => { entered = resolve; });
+ const change = withBotPermissionChangeForBot('bot-1', async () => {
+ runWorkerTx(sqlite, { name: 'bots.persistSessionPermission', args: { sessionId: 'chat', mode: 'ask' } });
+ entered();
+ await pending;
+ });
+ await started;
+ if (phase === 'completed') { release(); await change; }
+ try { expect(() => dispatch()).toThrow('Bot permissions changed before dispatch'); }
+ finally { release(); await change; }
+ state.stablePermissionModeState = { mode: 'ask' };
+ expect(() => dispatch()).toThrow('Bot permissions changed before dispatch');
+ const fresh = await prepareBotPermissionDispatch(runtime);
+ expect(() => fresh()).not.toThrow();
+ });
+
+ it('orders permission edits from main and topic without a cross-lane deadlock', async () => {
+ sqlite.exec(`INSERT INTO sessions (id,permission_mode,updated_at) VALUES ('topic','ask',1);
+ INSERT INTO bot_session_links VALUES ('bot-1','topic','thread',NULL);`);
+ let release!: () => void;
+ let entered!: () => void;
+ const pending = new Promise<void>(resolve => { release = resolve; });
+ const started = new Promise<void>(resolve => { entered = resolve; });
+ const live = { stablePermissionModeState: { mode: 'ask' }, setPermissionMode: vi.fn(async (mode: string) => {
+ if (mode === 'bypassPermissions') { entered(); await pending; }
+ live.stablePermissionModeState = { mode };
+ }) };
+ h.live.set('topic', live);
+ const main = persistPermissionModeWithoutRuntime('chat', 'bypassPermissions');
+ await started;
+ const topic = persistPermissionModeWithoutRuntime('topic', 'ask');
+ release();
+ await Promise.all([main, topic]);
+ // This is the cold persistence entry; its initiating topic has no runtime.
+ // The next normal reuse consumes the newly saved shared Ask choice.
+ await syncBotLanePermission('topic');
+ expect(sqlite.prepare('SELECT DISTINCT permission_mode FROM sessions').pluck().all()).toEqual(['ask']);
+ expect(live.stablePermissionModeState.mode).toBe('ask');
+ });
+
+ it('checks shared authority rather than a stale lane row and allows ordinary sibling repairs', 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);`);
+ const lane = { id: 'lane', stablePermissionModeState: { mode: 'bypassPermissions' } } as unknown as Session;
+ const stale = await prepareBotPermissionDispatch(lane);
+ expect(() => stale()).toThrow('Bot permissions changed before dispatch');
+ const main = { id: 'chat', stablePermissionModeState: { mode: 'ask' } } as unknown as Session;
+ const valid = await prepareBotPermissionDispatch(main);
+ await syncBotLanePermission('lane');
+ await withBotPermissionChangeForBot('another-bot', async () => {});
+ expect(() => valid()).not.toThrow();
+ });
+
it('does not replace a newer profile version with a stale capabilities snapshot', async () => {
sqlite.prepare('UPDATE bot_profiles SET current_version = 3 WHERE id = ?').run('bot-1');
sqlite.prepare('INSERT INTO bot_profile_versions VALUES (?, ?, ?)').run('bot-1', 3, '{"permissions":"ask","memory":false}');
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnObserver.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnObserver.test.ts
index 390c5e6b0b..cd19552bf7 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnObserver.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnObserver.test.ts
@@ -4,18 +4,20 @@ const h = vi.hoisted(() => ({
verdict: vi.fn(),
provider: vi.fn<(sessionId: string) => string | null>(),
ensureLlama: vi.fn(async () => undefined),
+ preparePermission: vi.fn(async () => () => {}),
}));
vi.mock('../../maker-host/model-route-guard-live.js', () => ({ verdictForModelRoute: h.verdict }));
vi.mock('../../maker-host/session-provider-store.js', () => ({ getSessionProvider: h.provider }));
vi.mock('../../local-model-runtime/preflight.js', () => ({ ensureManagedOllamaReadyForSession: h.ensureLlama }));
vi.mock('../../logger.js', () => ({ createLogger: () => ({ debug: vi.fn() }) }));
+vi.mock('../botPermissionDispatch.js', () => ({ prepareBotPermissionDispatch: h.preparePermission }));
import type { Session } from '@cindy/maker-core';
import { MANAGED_LLAMACPP_PROVIDER_ID } from '../../../shared/llamaCpp.js';
import { installSessionTurnObserver } from '../sessionTurnObserver.js';
-type Observer = { beforeProviderStart: (turnGeneration: number) => Promise<void> };
+type Observer = { beforeProviderStart: (turnGeneration: number) => Promise<void>; onDispatching?: () => void };
function setup(fields: { remoteHostId?: string | null; agentDeviceId?: string | null }) {
let observer: Observer | null = null;
@@ -38,7 +40,7 @@ function setup(fields: { remoteHostId?: string | null; agentDeviceId?: string |
log: { debug: vi.fn() },
};
installSessionTurnObserver(deps, session);
- return { deps, start: () => observer!.beforeProviderStart(1) };
+ return { deps, start: () => observer!.beforeProviderStart(1), dispatch: () => observer!.onDispatching?.() };
}
describe('installSessionTurnObserver provider precheck', () => {
@@ -46,10 +48,24 @@ describe('installSessionTurnObserver provider precheck', () => {
h.verdict.mockReset();
h.provider.mockReset();
h.ensureLlama.mockClear();
+ h.preparePermission.mockReset().mockResolvedValue(() => {});
h.verdict.mockResolvedValue({ kind: 'reject', reason: 'explicit-source-unavailable' });
h.provider.mockReturnValue('magpie-2e446a11');
});
+ // The common observer covers direct Desktop, IM and internal Session.send;
+ // preparation success cannot suppress its final permission authorization.
+ it('checks captured Bot permissions again at the synchronous provider boundary', async () => {
+ let current = true;
+ h.preparePermission.mockResolvedValue(() => { if (!current) throw new Error('permission changed'); });
+ h.verdict.mockResolvedValue({ kind: 'pass' });
+ const { start, dispatch } = setup({});
+ await start();
+ expect(() => dispatch()).not.toThrow();
+ current = false;
+ expect(() => dispatch()).toThrow('permission changed');
+ });
+
it('still rejects a local session whose explicit source is gone from this computer', async () => {
const { deps, start } = setup({});
await expect(start()).rejects.toMatchObject({ message: expect.stringContaining('magpie-2e446a11') });
diff --git a/apps/desktop/src/main/maker-ipc/botPermissionDispatch.ts b/apps/desktop/src/main/maker-ipc/botPermissionDispatch.ts
new file mode 100644
index 0000000000..f5d4a460bf
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/botPermissionDispatch.ts
@@ -0,0 +1,96 @@
+import type { Session } from '@cindy/maker-core';
+import { getCurrentDbClientSnapshot } from '../localDb/client/current.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+
+/** Account-local revisions bridge async persistence and the final synchronous provider call. */
+interface PermissionRevision {
+ revision: number;
+ pending: number;
+ idle: Promise<void>;
+ resolveIdle: () => void;
+ changes: Promise<void>;
+}
+const revisions = new WeakMap<object, Map<string, PermissionRevision>>();
+
+function revisionFor(owner: object, botId: string): PermissionRevision {
+ let bots = revisions.get(owner);
+ if (!bots) { bots = new Map(); revisions.set(owner, bots); }
+ let state = bots.get(botId);
+ if (!state) {
+ state = { revision: 0, pending: 0, idle: Promise.resolve(), resolveIdle: () => {}, changes: Promise.resolve() };
+ bots.set(botId, state);
+ }
+ return state;
+}
+
+export async function withBotPermissionChangeForBot<T>(
+ botId: string,
+ change: () => Promise<T>,
+): Promise<T> {
+ const owner = getCurrentDbClientSnapshot();
+ if (!owner) return change();
+ const state = revisionFor(owner, botId);
+ if (state.pending++ === 0) state.idle = new Promise(resolve => { state.resolveIdle = resolve; });
+ state.revision++;
+ const run = () => {
+ if (owner !== getCurrentDbClientSnapshot()) throwIpcError('PRECONDITION_FAILED', 'Account changed during permission update');
+ return change();
+ };
+ // Explicit edits from different lanes must share one commit order. Automatic
+ // repairs keep canonical/Profile authority unchanged and do not enter this queue.
+ const operation = state.changes.then(run);
+ state.changes = operation.then(() => undefined, () => undefined);
+ try { return await operation; }
+ finally { if (--state.pending === 0) state.resolveIdle(); }
+}
+
+export async function withBotPermissionChange<T>(
+ sessionId: string,
+ change: () => Promise<T>,
+): Promise<T> {
+ const owner = getCurrentDbClientSnapshot();
+ if (!owner) return change();
+ const [link] = await owner.client.query<{ botId: string }>(`SELECT bot_id AS botId FROM bot_session_links
+ WHERE session_id = ? AND role IN ('canonical', 'channel', 'group', 'thread') AND archived_at IS NULL`, [sessionId]);
+ if (owner !== getCurrentDbClientSnapshot()) throwIpcError('PRECONDITION_FAILED', 'Account changed during permission update');
+ return link ? withBotPermissionChangeForBot(link.botId, change) : change();
+}
+
+/** Capture after pending changes settle; check again synchronously after vision/authorization awaits. */
+export async function prepareBotPermissionDispatch(session: Session): Promise<() => void> {
+ const owner = getCurrentDbClientSnapshot();
+ if (!owner) return () => {};
+ const [link] = await owner.client.query<{ botId: string }>(`SELECT l.bot_id AS botId FROM bot_session_links l
+ JOIN sessions s ON s.id = l.session_id WHERE l.session_id = ?
+ AND l.role IN ('canonical', 'channel', 'group', 'thread') AND l.archived_at IS NULL
+ AND s.source = 'bot' AND s.status = 'active'`, [session.id]);
+ if (owner !== getCurrentDbClientSnapshot()) throwIpcError('PRECONDITION_FAILED', 'Account changed before dispatch');
+ if (!link) return () => {};
+ const state = revisionFor(owner, link.botId);
+ for (;;) {
+ if (owner !== getCurrentDbClientSnapshot()) throwIpcError('PRECONDITION_FAILED', 'Account changed before dispatch');
+ if (state.pending) { await state.idle; continue; }
+ const revision = state.revision;
+ // A saved lane may itself be the stale snapshot under repair. Read the
+ // authoritative canonical/Profile value, so repairs need no dispatch fence
+ // and concurrent ordinary sends do not invalidate one another.
+ const [row] = await owner.client.query<{ mode: string }>(`SELECT CASE
+ WHEN c.permission_mode IN ('ask', 'auto', 'bypassPermissions') THEN c.permission_mode
+ WHEN l.role = 'canonical' THEN s.permission_mode
+ ELSE CASE json_extract(v.capabilities_json, '$.permissions')
+ WHEN 'trusted' THEN 'bypassPermissions' WHEN 'auto' THEN 'auto' ELSE 'ask' END END AS mode
+ FROM bot_session_links l JOIN sessions s ON s.id = l.session_id
+ JOIN bot_profiles p ON p.id = l.bot_id
+ JOIN bot_profile_versions v ON v.bot_id = p.id AND v.version = p.current_version
+ LEFT JOIN bot_session_links cl ON cl.bot_id = p.id AND cl.role = 'canonical' AND cl.archived_at IS NULL
+ LEFT JOIN sessions c ON c.id = cl.session_id AND c.source = 'bot' AND c.status = 'active'
+ WHERE l.session_id = ? AND l.archived_at IS NULL AND s.status = 'active' AND p.status = 'active'`, [session.id]);
+ if (state.pending || state.revision !== revision) continue;
+ return () => {
+ if (owner !== getCurrentDbClientSnapshot() || state.pending || state.revision !== revision
+ || !row || session.stablePermissionModeState?.mode !== row.mode) {
+ throwIpcError('PRECONDITION_FAILED', 'Bot permissions changed before dispatch');
+ }
+ };
+ }
+}
diff --git a/apps/desktop/src/main/maker-ipc/botPermissionSync.ts b/apps/desktop/src/main/maker-ipc/botPermissionSync.ts
index 392201a163..cde2a3550a 100644
--- a/apps/desktop/src/main/maker-ipc/botPermissionSync.ts
+++ b/apps/desktop/src/main/maker-ipc/botPermissionSync.ts
@@ -61,13 +61,29 @@ export async function syncBotLinkedLanePermissions(canonicalSessionId: string):
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]);
+ WHERE c.session_id = ? AND c.role IN ('canonical', 'channel', 'group', 'thread') AND c.archived_at IS NULL
+ AND l.role IN ('canonical', 'channel', 'group', 'thread') AND l.archived_at IS NULL
+ AND l.session_id != c.session_id`, [canonicalSessionId]);
if (getCurrentDbClientSnapshot() !== owner) throw new Error('Account changed during lane permission update');
+ await syncBotPermissionRows(rows.map(row => row.sessionId));
+}
+
+/** Settings can outlive a missing canonical link; those live lanes still need tightening. */
+export async function syncBotPermissionsByBotId(botId: string, excludedSessionId = ''): Promise<void> {
+ const owner = getCurrentDbClientSnapshot();
+ if (!owner) return;
+ const rows = await owner.client.query<{ sessionId: string }>(`SELECT session_id AS sessionId
+ FROM bot_session_links WHERE bot_id = ? AND role IN ('canonical', 'channel', 'group', 'thread')
+ AND archived_at IS NULL AND session_id != ?`, [botId, excludedSessionId]);
+ if (getCurrentDbClientSnapshot() !== owner) throw new Error('Account changed during lane permission update');
+ await syncBotPermissionRows(rows.map(row => row.sessionId));
+}
+
+async function syncBotPermissionRows(sessionIds: string[]): Promise<void> {
// 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 results = await Promise.allSettled(sessionIds.map(sessionId => {
+ forgetCredentialGrants(sessionId);
+ return syncBotLanePermission(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.ts
index 883efea223..48c87a12cc 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -629,6 +629,7 @@ import { restartBotRuntime } from './botRuntimeRestart.js';
import { registerBotLifecycleHandlers } from './botLifecycleService.js';
import { isSessionPermissionMode, persistPermissionModeWithoutRuntime } from './sessionPermissionPersistence.js';
import { withSessionPermissionChange } from './sessionPermissionChange.js';
+import { withBotPermissionChange } from './botPermissionDispatch.js';
import { updateBotRoutineLifecycle } from '../routines/service.js';
import {
createBotCompactRuntimeRefreshCoordinator,
@@ -13601,7 +13602,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (result.response !== 0) return { granted: false };
// Reserve permission order before the lifecycle/restart fence. Ordinary
// permission writers never hold that fence while awaiting this queue.
- return await withSessionPermissionChange(task.taskId, () => service.completeOperation(() => withSessionRestartLock(task.taskId, async () => {
+ return await withBotPermissionChange(task.taskId, () => withSessionPermissionChange(task.taskId, () => service.completeOperation(() => withSessionRestartLock(task.taskId, async () => {
assertRequestCurrent();
if (snapshot !== getCurrentDbClientSnapshot() || before !== JSON.stringify(readPluginTaskConfig(pluginId))) throw new PluginTaskError('PERMISSION_DENIED', 'Account or permission settings changed');
const fresh = await service.get(pluginId, task.taskId);
@@ -13636,7 +13637,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (persisted) await snapshot!.client.tx('bots.persistSessionPermission', {sessionId: task.taskId, mode: task.permissionMode});
throw error;
}
- })));
+ }))));
});
} finally { pluginPermissionRequests.delete(pluginId); }
}
@@ -23507,7 +23508,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
throwIpcError('PRECONDITION_FAILED', 'Account changed during permission update');
}
};
- return withSessionPermissionChange(sessionId, async () => {
+ return withBotPermissionChange(sessionId, () => withSessionPermissionChange(sessionId, async () => {
assertOwnerCurrent();
await assertReviewSettingsUnlocked(sessionId);
assertOwnerCurrent();
@@ -23546,7 +23547,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
return result;
}
return true;
- });
+ }));
},
);
diff --git a/apps/desktop/src/main/maker-ipc/sessionPermissionPersistence.ts b/apps/desktop/src/main/maker-ipc/sessionPermissionPersistence.ts
index 21aed6b703..d13a82466b 100644
--- a/apps/desktop/src/main/maker-ipc/sessionPermissionPersistence.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionPermissionPersistence.ts
@@ -1,4 +1,5 @@
import { syncBotLinkedLanePermissions } from './botPermissionSync.js';
+import { withBotPermissionChange } from './botPermissionDispatch.js';
import { getCurrentDbClientSnapshot } from '../localDb/client/current.js';
const SESSION_PERMISSION_MODES = new Set([
@@ -33,8 +34,10 @@ export async function persistPermissionModeWithoutRuntime(
if (!isSessionPermissionMode(mode)) return false;
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;
+ return withBotPermissionChange(sessionId, async () => {
+ 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/apps/desktop/src/main/maker-ipc/sessionTurnObserver.ts b/apps/desktop/src/main/maker-ipc/sessionTurnObserver.ts
index 0aea1d5f67..3b5801eaa6 100644
--- a/apps/desktop/src/main/maker-ipc/sessionTurnObserver.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionTurnObserver.ts
@@ -9,6 +9,7 @@ import { isProviderShareAgentDeviceId } from '../../shared/providerShare.js';
import { verdictForModelRoute } from '../maker-host/model-route-guard-live.js';
import { describeModelRouteRejection } from '../maker-host/model-route-guard.js';
import { SilentStopTurnLeaseGate, SessionTurnLeaseTracker } from './sessionTurnLease.js';
+import { prepareBotPermissionDispatch } from './botPermissionDispatch.js';
export interface InstallSessionTurnObserverDeps {
readonly beforeLocalProviderStart?: (session: Session) => Promise<void>;
@@ -25,12 +26,16 @@ export interface InstallSessionTurnObserverDeps {
}
export function installSessionTurnObserver(deps: InstallSessionTurnObserverDeps, session: Session) {
+ let assertPermissionDispatch: (() => void) | undefined;
session.setTurnLifecycleObserver({
+ onDispatching: () => assertPermissionDispatch?.(),
beforeProviderStart: async (turnGeneration) => {
+ assertPermissionDispatch = undefined;
if (session.remoteHostId) {
await publishChannelTurn(session, 'starting');
return;
}
+ assertPermissionDispatch = await prepareBotPermissionDispatch(session);
await deps.beforeLocalProviderStart?.(session);
// 每条本地 Session.send 都经过这一个 Main-owned 边界,包括 renderer、IM、
// Goal、Learn、Hook 与 Scheduler。付费权限不能只挂在普通 IPC 发送事务上。
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index 9ffbb4faa5..f61a597fe0 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -129,12 +129,16 @@ Telegram 设为全响应的群;设置页的人格与行为配置不带。移
伙伴设为「完全访问」时三种 Agent 都无法兑现逐轮策略,成员触发的轮次同样按完全访问直接执行而不是被拒
跑——要成员动手前必须确认,把伙伴设成 Auto 或 Ask。连接不扩大任何权限。同一伙伴所有渠道共享记忆,不设每群记忆隔离。伙伴被删除时连接一并
停掉、清凭证、归档专线。连接记录是账号级设置(`bot-im-connections.json`),不含凭证。
-主任务显式切换 Ask / Auto / 完全访问时,当前 Profile 与有效的群、渠道、私聊话题专线
+主任务或有效群、渠道、私聊话题专线界面显式切换 Ask / Auto / 完全访问时,主任务、当前 Profile 与所有有效专线
在同一事务保存权限;已有运行实例随后热切换并广播,失败的实例关闭,不能继续使用旧的宽权限。
普通模型、身份与资料保存保留事务提交时的最新权限,只有显式权限编辑才能替换它;
较早读取的 Profile 快照不能在稍后保存时撤销主人刚完成的权限提升或收紧。
设置页与主任务显式切档共用包含数据库与运行态的完整提交顺序;即使保存界面当前显示的
同一档位,也按提交时的最新 Profile 对齐,不能因早读快照看似未变而漏写权限。
+设置页在主任务链接缺失时仍按伙伴枚举并同步存活专线,不因缺少主任务而跳过运行态收紧。
+同一伙伴不同入口的显式权限编辑共用提交顺序;发送准备期间若权限发生变化,宿主在最终
+同步派发边界拒绝这次旧权限发送,不能在数据库已收紧而实例尚未热切换时启动旧宽权限轮次。
+该检查由共享 Session 入口执行,覆盖桌面、IM 与内部发送;明确未派发的拒绝不等待不存在的模型尾事件。
存量权限冲突以当前有效主任务的 Ask / Auto / 完全访问档为准:创建、复用专线或发送前,
在同一事务将主任务当前档写回 Profile 与所有有效群、渠道、私聊话题专线,并同步已有运行实例。
例如主任务完全访问、Profile 与飞书专线为 Ask 时,自动统一为完全访问,不要求主人重新选档。
diff --git a/packages/maker-core/src/session.origin.test.ts b/packages/maker-core/src/session.origin.test.ts
index 43455e70bb..744404b5bb 100644
--- a/packages/maker-core/src/session.origin.test.ts
+++ b/packages/maker-core/src/session.origin.test.ts
@@ -150,6 +150,32 @@ function createControllableHandle(opts?: {
}
describe('dispatch authorization refresh', () => {
+ // Permission can change during preparation or even in the caller's final
+ // callback. The Host lifecycle check must still prevent any provider send.
+ it('runs the Host dispatch authorization last and unwinds a rejected reservation', async () => {
+ const h = createControllableHandle();
+ const send = vi.spyOn(h.handle, 'send');
+ const session = makeSession(h.handle);
+ let allowed = true;
+ const undispatched = vi.fn();
+ session.setTurnLifecycleObserver({
+ beforeProviderStart() {},
+ onDispatching() { if (!allowed) throw new Error('permission changed'); },
+ onUndispatched: undispatched,
+ onTerminal() {},
+ });
+ try {
+ await expect(session.send('prepared under old permission', {
+ onDispatching() { allowed = false; },
+ })).rejects.toThrow('permission changed');
+ expect(send).not.toHaveBeenCalled();
+ expect(undispatched).toHaveBeenCalledOnce();
+ allowed = true;
+ await expect(session.send('fresh permission')).resolves.toEqual({ accepted: true });
+ expect(send).toHaveBeenCalledOnce();
+ } finally { await session.close(); }
+ });
+
it.each([undefined, 'Earlier owner restriction'] as const)(
'preserves existing authorization when the final guard has no replacement: %s',
async (earlierIntent) => {
diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts
index 5f6381e2a9..48e668cdf4 100644
--- a/packages/maker-core/src/session.ts
+++ b/packages/maker-core/src/session.ts
@@ -355,6 +355,8 @@ export interface SessionSendOptions extends SendOptions {
}
export interface SessionTurnLifecycleObserver {
+ /** Last synchronous authorization check; no asynchronous work may follow before handle.send. */
+ onDispatching?(): void;
/** Awaited after option validation and before any provider-owned start hook or send. */
beforeProviderStart(turnGeneration: number): void | Promise<void>;
/** Called when a prepared generation never crosses the provider dispatch boundary. */
@@ -1008,6 +1010,14 @@ export class Session {
try {
this.beginTurnControl(reservedTurnGeneration);
onDispatching?.();
+ try {
+ turnLifecycleObserver?.onDispatching?.();
+ } catch (error) {
+ // Host authorization rejected synchronously, before handle.send could
+ // create work. Do not fence a later valid send for a nonexistent tail.
+ dispatchConfirmedUndispatched = true;
+ throw error;
+ }
this.insideProviderSendSync = true;
try {
await this.handle.send(msg, {