Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): align default routing and plugin authorization baseline
zqchris1bb46ab05459
diff --git a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.tsindex a3411a5790..d61a2bfd4c 100644--- a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts@@ -47,7 +47,7 @@ const useOrcaWorkerSelectionSource = readFileSync(useOrcaWorkerSelectionSourcePadescribe('sendToSession ordering', () => {it('routes even idle private Bot deliveries through the durable input coordinator', () => {const block = extractSendToSessionSource();- const routing = block.indexOf("explicitClientId?.startsWith('bot-dm:') || inputCoordinator.shouldQueueNewTurn(targetSessionId)");+ const routing = block.indexOf("explicitClientId?.startsWith('bot-dm:') || explicitClientId?.startsWith('bot-authorization-resume:') || inputCoordinator.shouldQueueNewTurn(targetSessionId)");expect(routing).toBeGreaterThan(0);expect(block.indexOf('await enqueueSendToSessionMessage({', routing)).toBeLessThan(block.indexOf('let live = maker.getSession(targetSessionId)'));});@@ -192,9 +192,10 @@ describe('sendToSession ordering', () => {);expect(workerReadyPlaceholderBlock).toContain('{ planMode: false, throwOnStartFailure: true },');expect(sendToSessionBlock).toContain('planMode: false,');- expect(queuedCreateOptsBlock).toContain('planMode: false,');+ expect(queuedCreateOptsBlock).toContain('inheritTargetPlanMode = false,');+ expect(queuedCreateOptsBlock).toContain('planMode: inheritTargetPlanMode ? !!row.planModeEnabled : false,');expect(orcaInterAgentDispatcherSource).toContain('planMode: false,');- expect(schedulerRunnerSource).toContain('planMode: false,');+ expect(schedulerRunnerSource).toContain('planMode: routinePermissions?.planMode ?? false,');expect(goalControllerSource).toContain("origin: { kind: 'goal', goalSessionId: sessionId },");expect(goalControllerSource).toContain('planMode: false,');expect(imTurnRunnerSource).toContain('planMode: false,');@@ -518,12 +519,12 @@ describe('sendToSession ordering', () => {);const directSendSwitchBlock = extractBetween(source,- 'pendingAgentSwitchApplyHolder = async (sessionId, signal) =>',+ 'pendingAgentSwitchApplyHolder = async (sessionId, signal, selection) =>','ipcMain.handle(MAKER_INVOKE.MARK_ORCA_ROLE',);expect(setModelBlock).toContain(- 'return withSendToSessionLock(sessionId, applyLocked);',+ 'return internalOptions.sessionLockHeld ? applyLocked() : withSendToSessionLock(sessionId, applyLocked);',);expect(setModelBlock).toContain('agentSwitchPending.revision?.(sessionId) !== expectedAgentSwitchRevision',@@ -607,7 +608,7 @@ describe('sendToSession ordering', () => {'applyPendingAgentSwitchIfIdle(',);expectOrder(directSendSwitchBlock, 'applyPendingAgentSwitchIfIdle(', 'prepareUnhealthySession');- expectOrder(directSendSwitchBlock, 'prepareUnhealthySession', 'return release;');+ expectOrder(directSendSwitchBlock, 'prepareUnhealthySession', 'return { release, selection: resolvedSelection };');});it('仅 Device Link 归一化 SET_MODEL 的 JSON null 可选占位,本地仍走严格校验', () => {diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex 874784d32b..1c8c60dda7 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -1646,10 +1646,12 @@ describe('Bot canonical Session lifecycle', () => {permissionMode: 'bypassPermissions',});- const first = await hydrateBotProfileRuntime(makeOpts(), {+ const initial = makeOpts();+ const first = await hydrateBotProfileRuntime(initial, {listSkills: async () => [],listOwnSkills: async () => ({ pluginRoot: '/userdata/bot-skills/bot-1', skills: [] }),});+ expect(initial.botProfileContextPrompt).toContain('save_bot_skill');await markBotProfileRuntimeApplied(first!);const resumed = makeOpts();diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.tsindex 35d75bf178..63a7a1a8b0 100644--- a/apps/desktop/src/main/localDb/ipc/bots.ts+++ b/apps/desktop/src/main/localDb/ipc/bots.ts@@ -4,7 +4,7 @@* 不维护第二份资料或决定 canonical Session。*/import { provisionDefaultBot } from '../../maker-ipc/botDefaultProvisioning.js';-import { BOT_TEMPLATE_PRESET_AVATARS, BOT_TEMPLATE_PRESET_IDENTITIES } from '../../../shared/botTemplatePreset.js';+import { BOT_TEMPLATE_PRESET_AVATARS, BOT_TEMPLATE_PRESET_IDENTITIES, CINDY_DEFAULT_IDENTITY } from '../../../shared/botTemplatePreset.js';import fs from 'node:fs/promises';import { randomUUID } from 'node:crypto';@@ -1320,7 +1320,7 @@ export function registerBotIpc(): void {return history.length > 0;},create: () => createBotProfile({ id: 'cindy-default', name: 'Cindy', templateId: 'cindy',- avatar: BOT_TEMPLATE_PRESET_AVATARS.cindy, identitySource: BOT_TEMPLATE_PRESET_IDENTITIES.cindy,+ avatar: BOT_TEMPLATE_PRESET_AVATARS.cindy, identitySource: CINDY_DEFAULT_IDENTITY,prepareInvitation: true }),});} catch (error) {diff --git a/apps/desktop/src/main/maker-host/__tests__/newMakerDefaultsCache.test.ts b/apps/desktop/src/main/maker-host/__tests__/newMakerDefaultsCache.test.tsindex 291a6d7c3e..122d6dc0ca 100644--- a/apps/desktop/src/main/maker-host/__tests__/newMakerDefaultsCache.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/newMakerDefaultsCache.test.ts@@ -7,6 +7,7 @@ import {getThinkingEnabledFromMemory,getWorkerDefaultsFromNewMaker,setNewMakerDraftCache,+ syncNewMakerDraftCache,setProviderModelMemoryCache,type NewMakerDraftSnapshot,} from '../newMakerDefaultsCache.js';@@ -167,3 +168,28 @@ it('does not reuse the selected default route across owners or older snapshots',setNewMakerDraftCache({ lastByVendor: {}, effortByModel: {}, fastModeByModel: {} }, 'owner-a');expect(getSelectedNewMakerRoute('owner-a')).toBeUndefined();});+++describe('owner-fenced new task and Bot default mirror', () => {+ const owner = { dataOwnerId: 'B', ownerGeneration: 3 };+ const route = { harness: 'codex', model: 'luna', providerId: 'openai', effort: 'medium', fastMode: false } as const;+ const payload = { ownerStamp: owner, selectedRoute: route, lastByVendor: { codex: { model: 'luna' } }, fastModeByModel: {}, effortByModel: {} };+ it('uses one accepted snapshot for ordinary task and Bot defaults', () => {+ expect(syncNewMakerDraftCache(payload, owner, 'B:3', false)).toBe(true);+ expect(getSelectedNewMakerRoute('B:3')).toEqual(route);+ expect(getRemoteNewMakerDefaults('codex').model).toBe('luna');+ });+ it.each([undefined, { dataOwnerId: 'A', ownerGeneration: 3 }, { dataOwnerId: 'B', ownerGeneration: 2 }])('rejects unstamped or late account snapshots: %j', (stamp) => {+ syncNewMakerDraftCache(payload, owner, 'B:3', false);+ expect(syncNewMakerDraftCache({ ...payload, ownerStamp: stamp, selectedRoute: { ...route, model: 'sol' } }, owner, 'B:3', false)).toBe(false);+ expect(getSelectedNewMakerRoute('B:3')).toEqual(route);+ });+ it('rejects a snapshot while the account boundary is pending', () => {+ expect(syncNewMakerDraftCache(payload, owner, 'B:3', true)).toBe(false);+ });+ it('clears the selected route when the current owner clears the default', () => {+ syncNewMakerDraftCache(payload, owner, 'B:3', false);+ syncNewMakerDraftCache({ ...payload, selectedRoute: undefined }, owner, 'B:3', false);+ expect(getSelectedNewMakerRoute('B:3')).toBeUndefined();+ });+});diff --git a/apps/desktop/src/main/maker-host/bot-model-chain-settings-store.ts b/apps/desktop/src/main/maker-host/bot-model-chain-settings-store.tsindex eab6bb9511..1e40c98546 100644--- a/apps/desktop/src/main/maker-host/bot-model-chain-settings-store.ts+++ b/apps/desktop/src/main/maker-host/bot-model-chain-settings-store.ts@@ -138,19 +138,26 @@ export async function resetBotModelChainSettings(* A null override means the permanent Bot Profile follows the owner-scoped* global route chain. Explicit per-Bot chains remain frozen in its profile.*/-export async function readEffectiveBotModelChain(+export async function readEffectiveBotModelSelection(config: Record<string, unknown>,- options?: { rootPath?: string; providers?: readonly ProviderView[]; availableAgents?: ReadonlySet<'cc' | 'codex' | 'pi'> },-): Promise<BotModelRoute[]> {+ options?: Parameters<typeof readBotModelChainSettingsState>[0],+): Promise<{ chain: BotModelRoute[]; followsCindyDefault: boolean }> {if (Array.isArray(config.modelChainOverride)) {const explicit = normalizeBotModelChain(config.modelChainOverride);- if (explicit.length > 0) return explicit;+ if (explicit.length > 0) return { chain: explicit, followsCindyDefault: false };}- // Before modelChainOverride existed, modelOverride:null was the durable- // marker for “follow the Bot default”. Preserve that meaning on upgrade.- if (config.modelChainOverride === null || config.modelOverride === null) {- return (await readBotModelChainSettings(options)).modelChain;+ // Preserve old explicit routes; null is the durable follow-default marker.+ if (config.modelChainOverride !== null && config.modelOverride !== null) {+ const legacy = normalizeBotModelChain(config.modelChain, config);+ if (legacy.length || typeof config.model === 'string') return { chain: legacy, followsCindyDefault: false };}- const legacy = normalizeBotModelChain(config.modelChain, config);- return legacy.length || typeof config.model === 'string' ? legacy : (await readBotModelChainSettings(options)).modelChain;+ const state = await readBotModelChainSettingsState(options);+ return { chain: state.value.modelChain, followsCindyDefault: !state.isCustomized };+}++export async function readEffectiveBotModelChain(+ config: Record<string, unknown>,+ options?: Parameters<typeof readBotModelChainSettingsState>[0],+): Promise<BotModelRoute[]> {+ return (await readEffectiveBotModelSelection(config, options)).chain;}diff --git a/apps/desktop/src/main/maker-host/newMakerDefaultsCache.ts b/apps/desktop/src/main/maker-host/newMakerDefaultsCache.tsindex 64cf652547..35163a19ab 100644--- a/apps/desktop/src/main/maker-host/newMakerDefaultsCache.ts+++ b/apps/desktop/src/main/maker-host/newMakerDefaultsCache.ts@@ -1,4 +1,5 @@-import type { BotModelRoute } from '../../shared/botModelChain.js';+import { normalizeBotModelChain, type BotModelRoute } from '../../shared/botModelChain.js';+import { isDataOwnerPushStamp, type DataOwnerPushStamp } from '../../shared/dataOwnerPush.js';import {DEFAULT_ORCA_WORKER_PERMISSION_MODE,resolveOrcaWorkerPermissionMode,@@ -78,6 +79,31 @@ export function setNewMakerDraftCache(snapshot: NewMakerDraftSnapshot, ownerScopselectedRouteOwner = ownerScope;}+/** One owner-fenced mirror for both ordinary task defaults and Bot defaults. */+export function syncNewMakerDraftCache(+ raw: unknown,+ activeOwner: DataOwnerPushStamp,+ ownerScope: string,+ boundaryPending: boolean,+): boolean {+ if (boundaryPending || !raw || typeof raw !== 'object' || Array.isArray(raw)) return false;+ const p = raw as Partial<NewMakerDraftSnapshot> & { ownerStamp?: unknown };+ if (!isDataOwnerPushStamp(p.ownerStamp)+ || p.ownerStamp.dataOwnerId !== activeOwner.dataOwnerId+ || p.ownerStamp.ownerGeneration !== activeOwner.ownerGeneration) return false;+ const record = (value: unknown) => !!value && typeof value === 'object' && !Array.isArray(value);+ if (!record(p.lastByVendor) || !record(p.fastModeByModel) || !record(p.effortByModel)) return false;+ setNewMakerDraftCache({+ selectedRoute: normalizeBotModelChain([p.selectedRoute])[0],+ lastByVendor: p.lastByVendor!,+ ...(record(p.modelChosenByVendor) ? { modelChosenByVendor: p.modelChosenByVendor } : {}),+ fastModeByModel: p.fastModeByModel!,+ effortByModel: p.effortByModel!,+ worktreeEnabled: p.worktreeEnabled === true,+ }, ownerScope);+ return true;+}+/** Renderer localStorage workerCreationPrefs 的 main 端内存镜像。 */export function setWorkerCreationPrefsCache(snapshot: WorkerCreationPrefsSnapshot): void {workerCreationPrefsCache = {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationHost.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationHost.test.tsindex 03665378c9..5e342b0160 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationHost.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationHost.test.ts@@ -11,22 +11,29 @@ const state = vi.hoisted(() => ({profileStatus: 'active',login: vi.fn(async () => ({ ok: true })),continued: vi.fn(),- policy: JSON.stringify({ toolsets: ['art'] }) as string | undefined,+ visible: true,+ realService: false,+ persistedCard: null as BotAuthorizationCard | null,deps: null as unknown as Parameters<typeof initBotAuthorizationService>[0],execute: vi.fn(async () => ({ ok: true })),}));vi.mock('electron', () => ({ shell: { openExternal: vi.fn() } }));vi.mock('../../i18n.js', () => ({ t: (key: string) => key }));vi.mock('../../logger.js', () => ({ createLogger: () => ({ warn: vi.fn() }) }));-vi.mock('../botAuthorizationService.js', () => ({- initBotAuthorizationService: (deps: typeof state.deps) => { state.deps = deps; },-}));+vi.mock('../botAuthorizationService.js', async (importOriginal) => {+ const actual = await importOriginal<typeof import('../botAuthorizationService.js')>();+ return { ...actual, initBotAuthorizationService: (deps: typeof state.deps) => {+ state.deps = deps;+ return state.realService ? new actual.BotAuthorizationService(deps) : undefined;+ } };+});vi.mock('../../localDb/client/current.js', () => ({getDbClient: () => ({ drizzle: { select: (fields: Record<string, unknown>) => {const query = {- from: () => query, innerJoin: () => query, where: () => query, orderBy: () => query,- limit: async () => 'resolvedJson' in fields- ? (state.policy === undefined ? [] : [{ resolvedJson: state.policy }])+ from: () => query, innerJoin: () => query, where: () => query,+ orderBy: async () => state.persistedCard ? [{ sessionId: 'session', meta: { botAuthorization: state.persistedCard } }] : [],+ limit: async () => 'meta' in fields+ ? (state.persistedCard ? [{ sessionId: 'session', meta: { botAuthorization: state.persistedCard } }] : []): [{ id: 'bot', workingDir: '/bot', status: state.profileStatus }],};return query;@@ -47,7 +54,9 @@ vi.mock('../../cindy-brain/index.js', () => ({acquireGhostMutationLeaseForMcp: () => () => {}, captureGhostMutationOwnerForMcp: () => ({}),}));vi.mock('../../cindy-brain/ghostVisibility.js', () => ({- classifyGhostVisibility: () => ({ ok: true, ghost: { manifest: { id: 'art', name: 'Art' } } }),+ classifyGhostVisibility: () => state.visible+ ? { ok: true, ghost: { manifest: { id: 'art', name: 'Art' } } }+ : { ok: false, errorCode: 'GHOST_DISABLED_IN_WORKDIR' },}));vi.mock('../../cindy-brain/ghostWorkdirPrefs.js', () => ({ isGhostDisabledForWorkdir: () => false }));vi.mock('../../cindy-brain/ghostSetupChangeBus.js', () => ({@@ -60,11 +69,13 @@ vi.mock('../../maker-host/grok-oauth-login.js', () => ({import { initializeBotAuthorizationHost } from '../botAuthorizationHost';const target = { kind: 'plugin' as const, id: 'art' };-describe('authorization Host frozen plugin policy', () => {+describe('authorization Host live plugin policy', () => {beforeEach(() => {state.assessment.mockReturnValue({ state: 'ready', revision: 1, groups: [] });state.subscribe.mockClear();- state.policy = JSON.stringify({ toolsets: ['art'] });+ state.visible = true;+ state.realService = false;+ state.persistedCard = null;state.save.mockClear();state.profileStatus = 'active';state.login.mockClear();@@ -76,6 +87,43 @@ describe('authorization Host frozen plugin policy', () => {});});+ it('runs the real Host and card lifecycle: dynamic plugin login saves a card and completion resumes once', async () => {+ state.realService = true;+ state.save.mockImplementation(async (_sessionId, message) => {+ state.persistedCard = structuredClone(message.agentMeta.botAuthorization);+ });+ state.assessment.mockReturnValue({ state: 'required', revision: 1, groups: [{+ id: 'account', mode: 'any_of', items: [{ ref: 'oauth:account', kind: 'oauth', label: 'Account', state: 'missing',+ actions: [{ id: 'connect', kind: 'oauth_connect' }] }],+ }] });+ const service = initializeBotAuthorizationHost(async (_card, validate, assertCurrent) => {+ await validate();+ assertCurrent();+ state.continued();+ });+ try {+ await expect(service.request('session', target)).resolves.toMatchObject({ ok: false, errorCode: 'SETUP_REQUIRED' });+ expect(state.persistedCard?.sessionId).toBe('session');+ expect(state.execute).not.toHaveBeenCalled();+ const card = state.persistedCard!;+ const sender = { id: 1, isDestroyed: () => false, send: vi.fn() };+ await service.resolve(card.snapshot.requestId, { kind: 'plugin_setup', action: 'run_action',+ actionId: card.snapshot.steps[0]!.action!.id, expectedRevision: card.snapshot.revision }, sender);+ await vi.waitFor(() => expect(state.execute).toHaveBeenCalledTimes(1));+ expect(state.continued).not.toHaveBeenCalled();+ state.assessment.mockReturnValue({ state: 'ready', revision: 2, groups: [] });+ for (const [, wake] of state.subscribe.mock.calls) {+ wake({ source: 'oauth' });+ wake({ source: 'oauth' });+ }+ await vi.waitFor(() => expect(state.continued).toHaveBeenCalledTimes(1));+ await vi.waitFor(() => expect(state.persistedCard?.snapshot.terminal).toBe(true));+ } finally {+ await service.dispose();+ state.save.mockReset();+ }+ });+it.each(['oauth_connect', 'inline_form'] as const)('checks the action generation after asynchronous Host validation for %s', async (kind) => {const adapter = await state.deps.adapter('session', target);let current = true;@@ -167,27 +215,29 @@ describe('authorization Host frozen plugin policy', () => {expect(state.continued).not.toHaveBeenCalled();});- it.each([undefined, '{', '{}', '{"toolsets":[]}'])('rejects restored cards without an applied grant: %s', async (policy) => {- state.policy = policy;- await expect(state.deps.adapter('session', target)).rejects.toThrow('disabled in teammate profile');- expect(state.execute).not.toHaveBeenCalled();- });-- it('rechecks the durable policy before assessment, credential mutation and continuation', async () => {+ it('rechecks live visibility before assessment, credential mutation and continuation', async () => {const adapter = await state.deps.adapter('session', target);await expect(adapter.assess()).resolves.toMatchObject({ state: 'ready' });- state.policy = JSON.stringify({ toolsets: [] });- await expect(adapter.assess()).rejects.toThrow('disabled in teammate profile');- await expect(adapter.execute({ id: 'connect', kind: 'oauth_connect' }, undefined)).rejects.toThrow('disabled in teammate profile');- await expect(state.deps.resume({ sessionId: 'session', target } as BotAuthorizationCard, () => {})).rejects.toThrow('disabled in teammate profile');+ state.visible = false; // plugin disabled/uninstalled or account no longer available+ await expect(adapter.assess()).rejects.toThrow('Plugin is unavailable');+ await expect(adapter.execute({ id: 'connect', kind: 'oauth_connect' }, undefined)).rejects.toThrow('Plugin is unavailable');+ await expect(state.deps.resume({ sessionId: 'session', target } as BotAuthorizationCard, () => {})).rejects.toThrow('Plugin is unavailable');expect(state.execute).not.toHaveBeenCalled();+ expect(state.continued).not.toHaveBeenCalled();+ });++ it('does not resume original work when a connection becomes incomplete again', async () => {+ await state.deps.adapter('session', target);+ state.assessment.mockReturnValue({ state: 'required', revision: 2, groups: [] });+ await expect(state.deps.resume({ sessionId: 'session', target } as BotAuthorizationCard, () => {})).rejects.toThrow('Plugin is not ready');+ expect(state.continued).not.toHaveBeenCalled();});- it('permits configured plugin actions and does not apply plugin policy to Host login', async () => {+ it('permits dynamically discovered plugin actions and does not apply plugin policy to Host login', async () => {const adapter = await state.deps.adapter('session', target);await expect(adapter.execute({ id: 'connect', kind: 'oauth_connect' }, undefined)).resolves.toMatchObject({ ok: true });expect(state.execute).toHaveBeenCalledTimes(1);- state.policy = undefined;+ state.visible = false;await expect(state.deps.adapter('session', { kind: 'host', id: 'grok' })).resolves.toMatchObject({ identity: { id: 'grok' } });});});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botModelRouteReconciler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botModelRouteReconciler.test.tsindex 0d799caddb..b1249014b1 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botModelRouteReconciler.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botModelRouteReconciler.test.ts@@ -1,4 +1,5 @@import { describe, expect, it, vi } from 'vitest';+import { withSendToSessionLock } from '../sendToSessionLock';import { createBotModelRouteReconciler } from '../botModelRouteReconciler';import type { BotModelRoute } from '../../../shared/botModelChain';import type { SessionRuntimeProfile } from '../sessionRuntimeControl';@@ -11,7 +12,7 @@ function harness() {hasRuntimeOverride: false,};const read = vi.fn(async () => state);- const apply = vi.fn(async () => undefined);+ const apply = vi.fn<Parameters<typeof createBotModelRouteReconciler>[0]['apply']>(async () => undefined);const reconcile = createBotModelRouteReconciler({ ownerEpoch: () => owner, read, apply });return { state, read, apply, reconcile, changeOwner: () => { owner = 'owner-b'; } };}@@ -24,6 +25,42 @@ describe('permanent Bot model selection', () => {expect(h.apply).not.toHaveBeenCalled();expect(await h.reconcile.preview('canonical')).toBeNull();});+ it('replaces an automatic runtime route when the Bot follows Cindy default', async () => {+ const h = harness();+ const state = { ...h.state, hasRuntimeOverride: true, followsCindyDefault: true };+ const reconcile = createBotModelRouteReconciler({ ownerEpoch: () => 'owner', read: async () => state, apply: h.apply });+ await expect(reconcile.preview('canonical')).resolves.toMatchObject({ model: 'luna', agentKind: 'codex' });+ await reconcile('canonical');+ expect(h.apply).toHaveBeenCalledWith('canonical', expect.objectContaining({ model: 'luna' }), state.current);+ });+ it('replaces a pending non-default route even when the live model still equals Cindy default', async () => {+ const h = harness();+ const current = { agentKind: 'codex' as const, model: 'luna', providerId: 'xd', effort: 'medium' as const, fastMode: false };+ const state = { ...h.state, current, next: { ...current, model: 'sol' }, hasRuntimeOverride: true, followsCindyDefault: true };+ const reconcile = createBotModelRouteReconciler({ ownerEpoch: () => 'owner', read: async () => state, apply: h.apply });+ await reconcile('canonical');+ expect(h.apply).toHaveBeenCalledWith('canonical', current, current);+ });+ it('reads a changed default after acquiring the ordinary send lock without deadlocking a lock holder', async () => {+ const h = harness();+ const reconcile = createBotModelRouteReconciler({ ownerEpoch: () => 'owner', read: h.read, apply: h.apply, withSessionLock: withSendToSessionLock });+ let release!: () => void;+ let inside!: () => Promise<void>;+ const holder = withSendToSessionLock('queued-model', async () => {+ inside = () => reconcile('queued-model', true);+ await new Promise<void>(resolve => { release = resolve; });+ });+ await vi.waitFor(() => expect(release).toBeTypeOf('function'));+ const waiting = reconcile('queued-model');+ h.state.chain[0]!.model = 'updated-default';+ // The lock holder can reconcile without waiting for the request behind it.+ await inside();+ expect(h.apply).toHaveBeenCalledWith('queued-model', expect.objectContaining({ model: 'updated-default' }), h.state.current);+ release();+ await holder;+ await waiting;+ expect(h.apply.mock.calls.every(([, route]) => route.model === 'updated-default')).toBe(true);+ });it('reads paused profiles only for previews and does not consume their pending model edits', async () => {const h = harness();let paused = true;diff --git a/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts b/apps/desktop/src/main/maker-ipc/botAuthorizationHost.tsindex 19b4cd7264..6826451317 100644--- a/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts+++ b/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts@@ -1,9 +1,9 @@import { getSessionRewindGeneration, withSendToSessionLock } from './sendToSessionLock.js';import { shell } from 'electron';import { t } from '../i18n.js';-import { and, eq, isNull, ne, or, gt, like, desc, inArray } from 'drizzle-orm';+import { and, eq, isNull, ne, or, gt, like, desc } from 'drizzle-orm';import { getDbClient } from '../localDb/client/current.js';-import { botSessionLinks, botProfiles, botRuntimeSnapshots, sessions, messages } from '../localDb/schema.js';+import { botSessionLinks, botProfiles, sessions, messages } from '../localDb/schema.js';import {createMessage,patchMessageAgentMeta,@@ -55,6 +55,7 @@ export async function isBotAuthorizationSession(sessionId: string): Promise<boolisNull(botSessionLinks.archivedAt),ne(sessions.status, 'deleted'),ne(sessions.status, 'archived'),+ isNull(sessions.remoteHostId),),).limit(1);@@ -67,30 +68,6 @@ export function initializeBotAuthorizationHost(captureInputGuard: (sessionId: string) => () => void = () => () => {},) {const ownerScopes = new Map<string, ReturnType<typeof captureDataOwnerBroadcastScope>>();- const assertPluginPolicy = async (sessionId: string, pluginId: string) => {- // The applied snapshot survives Host restarts; never infer teammate grants- // from global plugin visibility or from the card's display metadata.- const [snapshot] = await getDbClient()- .drizzle- .select({ resolvedJson: botRuntimeSnapshots.resolvedJson })- .from(botRuntimeSnapshots)- .where(- and(- eq(botRuntimeSnapshots.sessionId, sessionId),- inArray(botRuntimeSnapshots.status, ['applied', 'degraded']),- ),- )- .orderBy(desc(botRuntimeSnapshots.preparedAt))- .limit(1);- let resolved: { toolsets?: unknown } | null = null;- try {- resolved = JSON.parse(snapshot?.resolvedJson ?? 'null');- } catch {- /* deny malformed policy */- }- if (!Array.isArray(resolved?.toolsets) || !resolved.toolsets.includes(pluginId))- throw new Error('Plugin is disabled in teammate profile');- };const assertSession = async (sessionId: string) => {const scope = ownerScopes.get(sessionId);if (@@ -101,7 +78,7 @@ export function initializeBotAuthorizationHost()throw new Error('Authorization owner or teammate is unavailable');};- return initBotAuthorizationService({+ const service: Parameters<typeof initBotAuthorizationService>[0] = {async adapter(sessionId, target) {const scope = captureDataOwnerBroadcastScope();if (!scope) throw new Error('Authorization owner unavailable');@@ -179,8 +156,6 @@ export function initializeBotAuthorizationHost(.where(eq(sessions.id, sessionId)).limit(1);const validate = async () => {- await assertSession(sessionId);- await assertPluginPolicy(sessionId, target.id);await assertSession(sessionId);const result = classifyGhostVisibility(target.id, session?.workingDir ?? null, {listGhosts: () => getGhostManager().list(),@@ -361,8 +336,10 @@ export function initializeBotAuthorizationHost(async resume(card, assertCurrent) {await resume(card, async () => {await assertSession(card.sessionId);- if (card.target.kind === 'plugin')- await assertPluginPolicy(card.sessionId, card.target.id);+ if (card.target.kind === 'plugin') {+ const adapter = await service.adapter(card.sessionId, { ...card.target, reauthorize: false });+ if ((await adapter.assess()).state !== 'ready') throw new Error('Plugin is not ready');+ }const [row] = await getDbClient().drizzle.select({ id: messages.id }).from(messages)@@ -384,7 +361,8 @@ export function initializeBotAuthorizationHost(onDispose: () => ownerScopes.clear(),openExternal: (url) => shell.openExternal(url),warn: () => log.warn('Authorization card operation failed'),- });+ };+ return initBotAuthorizationService(service);}function readStoredAuthorization(row: {diff --git a/apps/desktop/src/main/maker-ipc/botModelRouteReconciler.ts b/apps/desktop/src/main/maker-ipc/botModelRouteReconciler.tsindex 0e3bba5b89..22fdff376e 100644--- a/apps/desktop/src/main/maker-ipc/botModelRouteReconciler.ts+++ b/apps/desktop/src/main/maker-ipc/botModelRouteReconciler.ts@@ -14,13 +14,14 @@ interface BotRouteState {chain: BotModelRoute[];current: RuntimeRoute;hasRuntimeOverride: boolean;+ followsCindyDefault?: boolean;next?: RuntimeRoute;}function configuredRoute(state: BotRouteState, previous: string | undefined, chain = state.chain): RuntimeRoute | null {const key = JSON.stringify(chain);const isDraftChange = key !== JSON.stringify(state.chain);- if (!isDraftChange && state.hasRuntimeOverride && (previous === undefined || previous === key)) return null;+ if (!state.followsCindyDefault && !isDraftChange && state.hasRuntimeOverride && (previous === undefined || previous === key)) return null;const primary = chain[0];if (!primary) return null;return {@@ -30,12 +31,18 @@ function configuredRoute(state: BotRouteState, previous: string | undefined, cha};}+function sameRoute(a: RuntimeRoute, b: RuntimeRoute): boolean {+ return a.agentKind === b.agentKind && a.model === b.model && a.providerId === b.providerId+ && a.effort === b.effort && a.fastMode === b.fastMode;+}+/** Apply the permanent profile through ordinary Session model/switch controls.* Fallback and Agent choices remain effective until the configured chain changes.* Background tasks keep their frozen route; the reader selects canonical tasks only.*/export function createBotModelRouteReconciler(deps: {ownerEpoch(): string;+ withSessionLock?<T>(sessionId: string, run: () => Promise<T>): Promise<T>;read(sessionId: string, purpose: 'apply' | 'preview'): Promise<BotRouteState | null>;apply(sessionId: string, route: RuntimeRoute, current: RuntimeRoute): Promise<void>;}) {@@ -51,11 +58,11 @@ export function createBotModelRouteReconciler(deps: {}return epoch;};- const reconcile = async (sessionId: string): Promise<void> => {+ const reconcile = async (sessionId: string, sessionLockHeld = false): Promise<void> => {const epoch = syncOwner();const existing = inFlight.get(sessionId);- if (existing) return existing;- const operation = (async () => {+ if (existing && !sessionLockHeld) return existing;+ const run = async () => {const state = await deps.read(sessionId, 'apply');if (deps.ownerEpoch() !== epoch) throw new Error('Bot model route owner changed');if (!state) {@@ -73,14 +80,16 @@ export function createBotModelRouteReconciler(deps: {return;}const current = state.current;- if (route.agentKind !== current.agentKind || route.model !== current.model- || route.providerId !== current.providerId || route.effort !== current.effort- || route.fastMode !== current.fastMode) {+ if (!sameRoute(route, current) || (state.next && !sameRoute(route, state.next))) {await deps.apply(sessionId, route, current);}if (deps.ownerEpoch() !== epoch) throw new Error('Bot model route owner changed');configured.set(sessionId, key);- })();+ };+ // Read after acquiring the same lock as ordinary sends. A caller already+ // inside that lock must never await an outside reconcile queued behind it.+ if (sessionLockHeld) return run();+ const operation = deps.withSessionLock ? deps.withSessionLock(sessionId, run) : run();inFlight.set(sessionId, operation);try { await operation; } finally {if (inFlight.get(sessionId) === operation) inFlight.delete(sessionId);diff --git a/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts b/apps/desktop/src/main/maker-ipc/botProfileRuntime.tsindex 85dfd667e6..b6a3951c09 100644--- a/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts+++ b/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts@@ -309,7 +309,7 @@ export function buildBotCapabilityContextPrompt(// tunnels cindy, so keep plugin guidance there.const cindyAvailable = options.cindyAvailable !== false;const pluginGuidance = cindyAvailable- ? ' Installed plugins are a separate discovery surface from Skill/MCP/toolset references. An empty capability search does not mean no plugin can do the work. Before declaring a connected-service task unavailable, inspect the relevant installed plugin. Installed plugins are available on demand through `cindy` (`ghost_list`, `ghost_info`, `ghost_call`) under their existing permissions.'+ ? ' Installed plugins are a separate discovery surface from Skill/MCP/toolset references. An empty capability search does not mean no plugin can do the work. Before declaring a connected-service task unavailable, inspect the relevant installed plugin. Installed plugins are available on demand through `cindy` (`ghost_list`, `ghost_info`, `ghost_call`) under their existing permissions. When a plugin returns SETUP_REQUIRED with an authorization request id, its login/configuration card is already in this chat and the requested tool has not run. End the turn and wait for the Host authorization-completed notification, then continue the original work through the live plugin tool. Do not poll, ask for credentials in chat, invent login links, or treat login as task execution approval. The phone can display/cancel the card; connection and secret entry happen on the trusted desktop.': '';return ['## Cindy Bot Runtime',@@ -825,7 +825,9 @@ export async function hydrateBotProfileRuntime(partnerActionsEnabled: row.role === 'canonical' && helperAvailable,routinesEnabled: row.role === 'canonical' && helperAvailable && !opts.remoteHostId,botCreationEnabled: row.role === 'canonical' && helperAvailable,- ownSkillsEnabled: ownSkillPluginRoot !== null,+ // Skill management is available before the first Skill exists. An empty+ // index must not hide the instructions for learning the first reusable method.+ ownSkillsEnabled: row.role === 'canonical' && helperAvailable && !opts.remoteHostId,botModeEnabled: row.role === 'canonical',};/*diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex abc78b69d1..19937cd8cb 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -363,7 +363,7 @@ import {} from '../localDb/schema.js';import { nextBotModelRoute, normalizeBotModelChain } from '../../shared/botModelChain.js';import { createBotModelRouteReconciler } from './botModelRouteReconciler.js';-import { readEffectiveBotModelChain } from '../maker-host/bot-model-chain-settings-store.js';+import { readEffectiveBotModelChain, readEffectiveBotModelSelection } from '../maker-host/bot-model-chain-settings-store.js';import {isOrcaWorkerPermissionMode,type OrcaWorkerPermissionMode,@@ -452,9 +452,8 @@ import {getRemoteNewMakerDefaultsByVendor,getWorkerDefaultsFromNewMaker,getWorkerPermissionModeFromCreationPrefs,- type NewMakerDraftSnapshot,type ProviderModelMemorySnapshot,- setNewMakerDraftCache,+ syncNewMakerDraftCache,setProviderModelMemoryCache,setWorkerCreationPrefsCache,} from '../maker-host/newMakerDefaultsCache.js';@@ -4590,6 +4589,14 @@ let disposePiPackagesChangedBroadcast: (() => void) | null = null;* soon as the Renderer selects an owner, before the splash-gated Maker IPC bundle is available.*/export function registerModelVisibilitySyncIpc(): void {+ // Register with model visibility before the first window; a cold-start preference+ // push must not be lost while the larger Maker bundle is still initializing.+ ipcMain.on(MAKER_SEND.SYNC_NEW_MAKER_DRAFT, (event, payload: unknown) => {+ assertTrustedAppRendererEvent(event);+ if (syncNewMakerDraftCache(payload, getActiveDataOwnerPushStamp(),+ activeOwnerScopeKey(), isAppSessionBoundaryPending())) broadcastNewMakerDraftChanged();+ });+ipcMain.handle(MAKER_INVOKE.MODEL_VISIBILITY_SYNC,async (event, dataOwnerId: unknown, ownerGeneration: unknown, map: unknown, policy?: unknown) => {@@ -4760,38 +4767,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions));initRenameSessionsConfirm(renameSessionsConfirmBridge);- // ── newMakerDraft 缓存同步 ──────────────────────────────────────────────- // Renderer push (fire-and-forget) → main 内存缓存; collab spawn worker 时- // 读这份缓存决定 model/effort/fastMode。startup 立刻推一次 + 用户每次改 New- // Maker 偏好时增量推(含每个 vendor 的显式模型选择状态),payload 形态严格按- // newMakerDefaultsCache.NewMakerDraftSnapshot。- // 校验失败 (payload 不是 object / 缺字段) → no-op, 缓存维持上一次值, 避免脏数据污染。- ipcMain.on(MAKER_SEND.SYNC_NEW_MAKER_DRAFT, (_e, payload: unknown) => {- if (!payload || typeof payload !== 'object') return;- const p = payload as Partial<NewMakerDraftSnapshot>;- if (- !p.lastByVendor ||- typeof p.lastByVendor !== 'object' ||- !p.fastModeByModel ||- typeof p.fastModeByModel !== 'object' ||- !p.effortByModel ||- typeof p.effortByModel !== 'object'- )- return;- setNewMakerDraftCache({- selectedRoute: normalizeBotModelChain([p.selectedRoute])[0],- lastByVendor: p.lastByVendor,- ...(p.modelChosenByVendor && typeof p.modelChosenByVendor === 'object'- ? { modelChosenByVendor: p.modelChosenByVendor }- : {}),- fastModeByModel: p.fastModeByModel,- effortByModel: p.effortByModel,- // worktree 勾选记忆(vendor 无关根字段):旧 renderer 不推此字段 → false 兜底。- worktreeEnabled: p.worktreeEnabled === true,- }, activeOwnerScopeKey());- broadcastNewMakerDraftChanged();- });-// Worker 创建偏好与模型默认值同样以 renderer localStorage 为真源。main 只保留// 权限模式镜像,供 Orca UI / MCP 创建路径读取。ipcMain.on(@@ -8177,6 +8152,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)pendingAgentSwitchApplyHolder = async (sessionId, signal, selection) => {const release = await acquireSendToSessionLock(sessionId);try {+ await reconcileBotModelRoute(sessionId, true);await applyPendingAgentSwitchIfIdle(agentSwitchDeps, sessionId, {bootstrapAfterSwitch: true,signal,@@ -8703,6 +8679,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// await 上,日志即可直接定位挂点(PR #2829 QA:回执 deliver 挂死 64 分钟零线索)。let lockStage = 'resolve-session-meta+row';const run = waitPrev.then(async () => {+ await reconcileBotModelRoute(targetSessionId, true);const [meta, dbRow] = await Promise.all([maker.getSessionMeta(targetSessionId).catch(() => null),getSessionRowSnapshot(targetSessionId),@@ -10853,6 +10830,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const reconcileBotModelRoute = createBotModelRouteReconciler({ownerEpoch: captureSessionRuntimeControlOwnerEpoch,+ withSessionLock: withSendToSessionLock,read: async (sessionId, purpose) => {const [row] = await getDbClient().drizzle.select({capabilitiesJson: botProfileVersions.capabilitiesJson,@@ -10880,11 +10858,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)eq(sessions.status, 'active'),)).limit(1);if (!row) return null;- const chain = await readEffectiveBotModelChain(JSON.parse(row.capabilitiesJson));+ const selection = await readEffectiveBotModelSelection(JSON.parse(row.capabilitiesJson));const control = getSessionRuntimeControlSnapshot(sessionId);const live = maker.getSession(sessionId);return {- chain,+ chain: selection.chain,+ followsCindyDefault: selection.followsCindyDefault,current: {agentKind: live?.agentKind ?? dbToMakerAgentKind(row.agentKind),model: live?.model ?? row.model ?? '',@@ -10901,18 +10880,18 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (route.agentKind !== current.agentKind) {// Register the ordinary switch intent. Its existing send transaction// parks the native binding and hands history to the chosen harness.- await withSendToSessionLock(sessionId, () => performSessionAgentSwitch(agentSwitchDeps, {+ await performSessionAgentSwitch(agentSwitchDeps, {sessionId,targetAgentKind: route.agentKind,model: route.model,providerId: route.providerId,effort: route.effort,fastMode: route.fastMode,- }));+ });} else {const result = await applySessionRuntimeSelection(sessionId, route.model, route.providerId,{ effort: route.effort as SessionRuntimeProfile['effort'], fastMode: route.fastMode },- { source: 'user', deferWhileRunning: true });+ { source: 'user', deferWhileRunning: true, sessionLockHeld: true });if (runtimeSelectionRequiresModelWindowConfirmation(result)) {throwIpcError('PRECONDITION_FAILED', 'Model context window confirmation is required');}@@ -11932,6 +11911,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const compactedRuntime = maker.getSession(sessionId);if (compactedRuntime) await refreshBotCapabilityEpochBeforeSend(compactedRuntime);return await withSendToSessionLock(sessionId, async () => {+ await reconcileBotModelRoute(sessionId, true);const [botInput] = await getDbClient().drizzle.select({source: sessions.source,diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.tsindex 4ae27c8874..8706d036e7 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts@@ -749,23 +749,13 @@ describe('写路径 roundtrip(真实存储,tmp userData)', () => {});});-describe('connect_account frozen plugin policy', () => {- it.each([- { __cindyAllowedBuiltinPluginIds: ['other'] },- { __cindyDisabledBuiltinPluginIds: ['art'] },- ])('rejects a disabled plugin before creating a card: %j', async (policy) => {- const deps = makeDeps('claude-code', 'bot-session', 'bot-instance', policy);- await expect(deps.connectAccount!({ kind: 'plugin', id: 'art' })).resolves.toMatchObject({- ok: false, errorCode: 'GHOST_DISABLED_IN_WORKDIR',- });- expect(authorizationRequestMock).not.toHaveBeenCalled();- });-- it('allows an enabled plugin and keeps Host login independent of plugin policy', async () => {+describe('connect_account shares Host live plugin policy', () => {+ it('passes dynamically discovered plugins to Host without treating builtin toolsets as plugin grants', async () => {const deps = makeDeps('claude-code', 'bot-session', 'bot-instance', {- __cindyAllowedBuiltinPluginIds: ['art'],+ __cindyAllowedBuiltinPluginIds: ['memory', 'xdt_helper'],});await deps.connectAccount!({ kind: 'plugin', id: 'art' });+ expect(authorizationRequestMock).toHaveBeenCalledWith('bot-session', { kind: 'plugin', id: 'art' });await deps.connectAccount!({ kind: 'host', id: 'grok' });expect(authorizationRequestMock).toHaveBeenCalledTimes(2);});diff --git a/apps/desktop/src/main/mcp-integrations/ghost.ts b/apps/desktop/src/main/mcp-integrations/ghost.tsindex ec26e5aa65..509f5907f3 100644--- a/apps/desktop/src/main/mcp-integrations/ghost.ts+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts@@ -107,7 +107,6 @@ import { ghostSetupInteractionSessionId } from './ghostSetupInteractionSurface.jimport { createForgeIconConverter } from './forgeIconConversion.js';import { forkForgeIconConversionHost } from './forgeIconConversionHost.js';import {- isFrozenBuiltinPluginAllowed,readAllowedBuiltinPluginIds,} from './codexBuiltinToolPolicy.js';import { t } from '../i18n.js';@@ -1355,17 +1354,8 @@ export function getCindyGhostsMcpDeps(): CindyGhostsMcpDeps {const resolveSessionContext = (): LiziMcpSessionContext | undefined =>getLiziMcpSessionContext() ?? sessionCtx;- const isGhostAllowedByFrozenProfile = (ghostId: string): boolean =>- isFrozenBuiltinPluginAllowed(resolveSessionContext()?.vendorOptions, ghostId);- const frozenProfileDenied = () => ({- ok: false as const,- errorCode: 'GHOST_DISABLED_IN_WORKDIR' as const,- message: '当前伙伴配置未启用该插件;不要重试,改用已授权能力,或让用户更新伙伴配置后再试。',- });return {connectAccount: async (target) => {- if (target.kind === 'plugin' && !isGhostAllowedByFrozenProfile(target.id))- return frozenProfileDenied();const context = resolveSessionContext();const sessionId = ghostSetupInteractionSessionId(context);if (!sessionId) return { ok: false, errorCode: 'NO_SESSION_CONTEXT' };@@ -1438,8 +1428,7 @@ export function getCindyGhostsMcpDeps(//// 伙伴冻结 Toolset 只清空本花名册快照(不把全量插件写进工具描述);// ghost_list / ghost_info / ghost_call 仍按实时可见性发现已装插件,- // 内置工具冻结名单不套到插件 ID。connect_account 对 plugin 目标另走- // 冻结门禁,避免未授权插件直接发卡。+ // 内置工具冻结名单不套到插件 ID;授权卡同样由 Host 按实时插件可见性守门。getRosterItems() {const context = resolveSessionContext();const workdir = context?.workingDir;diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 955cd4d258..2183b37b2e 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -2432,6 +2432,7 @@ contextBridge.exposeInMainWorld('electronAPI', {* fire-and-forget。*/syncNewMakerDraft: (snapshot: {+ ownerStamp: import('../shared/dataOwnerPush').DataOwnerPushStamp;selectedRoute?: import('../shared/botModelChain').BotModelRoute;lastByVendor: Partial<Record<diff --git a/apps/desktop/src/renderer/App.tsx b/apps/desktop/src/renderer/App.tsxindex 9abe5aa034..375e98ac2b 100644--- a/apps/desktop/src/renderer/App.tsx+++ b/apps/desktop/src/renderer/App.tsx@@ -1,3 +1,4 @@+import { getDataOwnerGeneration } from './contexts/dataOwnerGeneration';import { RouterProvider } from 'react-router-dom';import { useEffect } from 'react';@@ -48,7 +49,7 @@ import {} from '@/lib/localCatalogSnapshot';import { useResyncAgentIslandSettingsAfterLogin } from '@/hooks/useAgentIslandSettings';import {- getDraftForPreferenceSync,+ getDraftForOwnerPreferenceSync,subscribeDraft,setEffortForModel,setFastModeForModel,@@ -99,7 +100,9 @@ function LoginHandoffHost({ children }: { children: React.ReactNode }) {function syncNewMakerPrefs() {// 多 renderer 的模块内存彼此独立;跨窗口通知必须从共享持久快照同步,避免旧窗口把// 自己的 model / workingDir 等完整旧草稿覆盖进 main 缓存。- const draft = getDraftForPreferenceSync();+ const owner = getDataOwnerGeneration();+ const draft = getDraftForOwnerPreferenceSync(owner.dataOwnerId);+ if (!draft) return;const cc = draft.lastByVendor.cc;window.electronAPI.syncDesktopCcPrefs({model: cc.model,@@ -116,6 +119,7 @@ function syncNewMakerPrefs() {// 不消费这两项,远程草稿镜像才用)。fire-and-forget。const selected = draft.lastByVendor[draft.vendor];window.electronAPI.syncNewMakerDraft({+ ownerStamp: { dataOwnerId: owner.dataOwnerId, ownerGeneration: owner.generation },selectedRoute: {harness: draft.vendor === 'cc' || draft.vendor === 'orca' ? 'claude' : draft.vendor,providerId: selected.providerId ?? null,diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.tsindex f2bcca46aa..6957edf9c2 100644--- a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts+++ b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts@@ -1273,7 +1273,7 @@ describe('远程交互接线不变式', () => {it('跨窗口 worktree 写穿只合并目标字段,main 镜像读取共享持久快照', () => {const src = read('App.tsx');- expect(src).toContain('const draft = getDraftForPreferenceSync();');+ expect(src).toContain('const draft = getDraftForOwnerPreferenceSync(owner.dataOwnerId);');expect(src).toContain('setWorktreePreference(worktreeEnabled === true);');expect(src).not.toContain('patchDraft({ worktreeEnabled: worktreeEnabled === true });');});diff --git a/apps/desktop/src/renderer/__tests__/newMakerDraft.test.ts b/apps/desktop/src/renderer/__tests__/newMakerDraft.test.tsindex b08a8545aa..37acfac39c 100644--- a/apps/desktop/src/renderer/__tests__/newMakerDraft.test.ts+++ b/apps/desktop/src/renderer/__tests__/newMakerDraft.test.ts@@ -1810,3 +1810,14 @@ describe('newMakerDraft store', () => {});});});+++it('does not stamp a prior owner draft during the synchronous auth handoff', async () => {+ const { setNewMakerDraftOwner, getDraftForOwnerPreferenceSync, patchCurrentVendorPrefs } = await loadModule();+ setNewMakerDraftOwner('A');+ patchCurrentVendorPrefs({ model: 'owner-a-model' });+ expect(getDraftForOwnerPreferenceSync('B')).toBeNull();+ setNewMakerDraftOwner('B');+ expect(getDraftForOwnerPreferenceSync('B')?.lastByVendor.cc.model).not.toBe('owner-a-model');+ expect(getDraftForOwnerPreferenceSync('A')).toBeNull();+});diff --git a/apps/desktop/src/renderer/features/bots/botTemplates.ts b/apps/desktop/src/renderer/features/bots/botTemplates.tsindex d8b5551960..539aa5ee1b 100644--- a/apps/desktop/src/renderer/features/bots/botTemplates.ts+++ b/apps/desktop/src/renderer/features/bots/botTemplates.ts@@ -1,6 +1,7 @@import {BOT_TEMPLATE_PRESET_AVATARS,BOT_TEMPLATE_PRESET_IDENTITIES,+ CINDY_DEFAULT_IDENTITY,type BotTemplatePresetId,} from '../../../shared/botTemplatePreset';@@ -28,7 +29,7 @@ export const BOT_TEMPLATES: readonly BotTemplateDefinition<BotTemplateId>[] = [avatarColor: 'blue',translationKey: 'cindy',toolsets: ['docs'],- identitySource: BOT_TEMPLATE_PRESET_IDENTITIES.cindy,+ identitySource: CINDY_DEFAULT_IDENTITY,},{id: 'dash',diff --git a/apps/desktop/src/renderer/state/newMakerDraft.ts b/apps/desktop/src/renderer/state/newMakerDraft.tsindex 17da766fe3..a6fe4f3689 100644--- a/apps/desktop/src/renderer/state/newMakerDraft.ts+++ b/apps/desktop/src/renderer/state/newMakerDraft.ts@@ -746,6 +746,11 @@ export function getDraftForPreferenceSync(): NewMakerDraft {: persistedDraft;}+/** Do not stamp a previous owner's draft during the auth namespace handoff. */+export function getDraftForOwnerPreferenceSync(ownerId: string | null): NewMakerDraft | null {+ return activeDataOwnerId === ownerId ? getDraftForPreferenceSync() : null;+}+/** Switch the persistent draft namespace together with the active data owner. */export function setNewMakerDraftOwner(ownerId: string | null): void {const normalized = typeof ownerId === 'string' && ownerId.trim().length > 0 ? ownerId : null;diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex d997910ebb..d42410eb3d 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -2400,6 +2400,7 @@ interface ElectronAPI {}) => void;syncNewMakerDraft: (snapshot: {+ ownerStamp: import('../shared/dataOwnerPush').DataOwnerPushStamp;selectedRoute?: import('../shared/botModelChain').BotModelRoute;lastByVendor: Partial<Record<diff --git a/apps/desktop/src/shared/__tests__/botTemplatePreset.test.ts b/apps/desktop/src/shared/__tests__/botTemplatePreset.test.tsnew file mode 100644index 0000000000..c7d24a7086--- /dev/null+++ b/apps/desktop/src/shared/__tests__/botTemplatePreset.test.ts@@ -0,0 +1,14 @@+import { describe, expect, it } from 'vitest';+import { BOT_TEMPLATE_PRESET_IDENTITIES, CINDY_DEFAULT_IDENTITY, inferBotTemplatePresetId } from '../botTemplatePreset';++describe('Cindy identity compatibility', () => {+ it('recognizes both the shipped legacy identity and the new client partner identity', () => {+ expect(inferBotTemplatePresetId(BOT_TEMPLATE_PRESET_IDENTITIES.cindy)).toBe('cindy');+ expect(inferBotTemplatePresetId(CINDY_DEFAULT_IDENTITY)).toBe('cindy');+ });+ it('never infers a template after the user customizes either identity', () => {+ for (const identity of [BOT_TEMPLATE_PRESET_IDENTITIES.cindy, CINDY_DEFAULT_IDENTITY]) {+ expect(inferBotTemplatePresetId(identity + '\nMy own instructions')).toBeNull();+ }+ });+});diff --git a/apps/desktop/src/shared/botTemplatePreset.ts b/apps/desktop/src/shared/botTemplatePreset.tsindex 7bbebec85c..db7acf945e 100644--- a/apps/desktop/src/shared/botTemplatePreset.ts+++ b/apps/desktop/src/shared/botTemplatePreset.ts@@ -45,7 +45,16 @@ export const BOT_TEMPLATE_PRESET_IDENTITIES: Record<BotTemplatePresetId, string>].join('\n\n'),};+/** New installations; the legacy identity above remains an exact migration fingerprint. */+export const CINDY_DEFAULT_IDENTITY = [+ '# 身份\n你是 Cindy,Cindy 客户端里的默认伙伴。你帮助用户使用客户端和已连接的工具完成工作;你不是整个客户端,也不代替用户拥有账号和权限。',+ '# 工作\n处理写作、整理、分析、计划和日常事务。简单工作直接完成;编码实施和中大型工作使用独立任务,跟进结果并核对后交付。伙伴间消息用于必要沟通,不代替独立任务。',+ '# 方式\n先理解用户想得到的结果,再用实际可用的工具行动。需要外部服务时先查已安装插件并复用已有连接;按宿主提供的授权卡完成缺失的连接。',+ '# 相处\n表达自然、简洁、具体。保留用户已给出的要求和授权;不编造背景、能力或完成状态,不反复询问已经明确的事情。',+].join('\n\n');+export function inferBotTemplatePresetId(identitySource: string): BotTemplatePresetId | null {+ if (identitySource === CINDY_DEFAULT_IDENTITY) return 'cindy';return (BOT_TEMPLATE_PRESET_IDS.find((templateId) => BOT_TEMPLATE_PRESET_IDENTITIES[templateId] === identitySource,diff --git a/docs/product-rules/bot-authorization-cards.md b/docs/product-rules/bot-authorization-cards.mdindex ee683ba991..d6e5aa3211 100644--- a/docs/product-rules/bot-authorization-cards.md+++ b/docs/product-rules/bot-authorization-cards.md@@ -36,7 +36,8 @@ Grok 的 MCP 后端 state TTL 不能直接套给 Grok 订阅登录或所有插## 兼容与已有 PR- #4058 的插件发现、能力装配、授权继承保持独立,本改动不复制其实现。伙伴默认发现 `cindy`- 入口需要该 PR;只合本改动时已有显式装配入口可用,其它伙伴保留原有能力面。+ 入口由公共运行时提供。插件发卡、操作和续接按当前账号、安装启停与工作目录的实时+ 可见性判断;内置工具集的冻结名单不作为插件 ID 的授权清单。续接前再次核对真实配置就绪。- #4066 的发送与各 harness 工具暴露修复不在本改动重复实现。两边无新 schema 依赖,可分别合入。- 不修改插件 manifest、安装批准记录、凭证布局或数据库 schema;不要求存量插件重新配置。- 手机经已有消息同步显示授权状态并可取消,授权/密钥输入仍在可信电脑端。无原生指纹变更。diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex 1acd62107d..493e509e17 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -132,7 +132,7 @@ harness + provider + model + effort + fastMode该伙伴保存自己的链。全局链由主进程按当前数据 owner 持久化,并由所有 Session 创建与 fallback入口直接读取;不得只存在 renderer localStorage。-发送前按持久 Profile 协调长期主任务的路由,复用普通任务的模型控制与跨引擎交接。配置未变时保留运行期 fallback;用户改变候选链后按新选择执行。后台任务继承发起时的实际路由,不读取可能过时的主任务创建模型。+发送前按持久 Profile 协调长期主任务的路由,复用普通任务的模型控制与跨引擎交接。显式候选链未变时保留运行期 fallback;跟随 Cindy 默认时每次核对当前唯一可用默认,不沿用自动切出的其它型号。用户改变候选链后按新选择执行。后台任务继承发起时的实际路由,不读取可能过时的主任务创建模型。## 6. Skill、工具与 MCP@@ -293,3 +293,9 @@ Session 任务遵守同一套机制与呈现契约:- 第一条回复由伙伴自身运行时根据身份和记忆生成,沿用流式输出和消息去重。旧客户端提交的预写问候只作为请求问候的兼容信号,不会写成 assistant 消息。没有可用模型时等待配置,绝不偷选其它模型。- 已有用户的身份、模型 override、授权、自有 Skill、记忆和历史不被新基准覆盖;进行中的工作不被重启。+++默认模型镜像与新建任务共用现有草稿真相源。同步入口在首个窗口创建前注册,快照必须携带+当前数据 owner 与代次;切换期间、旧账号或旧代次的迟到快照不得覆盖当前默认。+没有自有 Skill 的新伙伴也具备学习入口;空技能索引只表示尚未沉淀,不关闭技能管理能力。+插件登录/配置使用 [伙伴授权卡](bot-authorization-cards.md),与独立任务的执行授权分别处理。