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: coordinate archived runtime settings under the send lease

Dash6bd71790e741
diff --git a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
index 6c3492e78c..5ab962cbd6 100644
--- a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
+++ b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
@@ -2,6 +2,7 @@ import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import ts from 'typescript';
import { describe, expect, it, vi } from 'vitest';
+import { createEffortChangeCoordinator, enqueueEffortChange } from '../../renderer/components/new-chat/effortChangeQueue';
const mainRoot = resolve(__dirname, '..');
const bootstrapSource = readFileSync(resolve(mainRoot, 'bootstrap-electron.ts'), 'utf8').replace(
@@ -59,7 +60,7 @@ const isUserPendingAgentSwitchIntent = new Function(ts.transpileModule(
).outputText)();
function collectAxisHandlers(node: ts.Node): void {
if (ts.isVariableDeclaration(node) && node.initializer &&
- ['applyEffort', 'applyFastMode', 'stagePendingUserRuntimeAxis'].includes(node.name.getText(registerAst))) {
+ ['applyEffort', 'applyFastMode', 'persistEffort', 'persistFastMode', 'stagePendingUserRuntimeAxis'].includes(node.name.getText(registerAst))) {
axisHandlers.set(node.name.getText(registerAst), ts.transpileModule(
`return ${node.initializer.getText(registerAst)};`,
{ compilerOptions: { target: ts.ScriptTarget.ES2022 } },
@@ -68,22 +69,37 @@ function collectAxisHandlers(node: ts.Node): void {
ts.forEachChild(node, collectAxisHandlers);
}
collectAxisHandlers(registerAst);
+// Cross-file persistence contract: the real Renderer adapter must leave the
+// decision to Main even before its pending-intent projection reaches this UI.
+const rendererStoreAst = ts.createSourceFile('store.ts', readFileSync(
+ resolve(mainRoot, '../renderer/lib/makerChatStore.ts'), 'utf8'), ts.ScriptTarget.Latest, true);
+const rendererInputAst = ts.createSourceFile('ChatInput.tsx', readFileSync(
+ resolve(mainRoot, '../renderer/components/new-chat/ChatInput.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+const fastSetter = rendererStoreAst.statements.find((node): node is ts.FunctionDeclaration =>
+ ts.isFunctionDeclaration(node) && node.name?.text === 'setFastMode')!;
+let effortPipeline = '';
+function findEffortPipeline(node: ts.Node): void {
+ if (ts.isCallExpression(node) && node.expression.getText(rendererInputAst) === 'enqueueEffortChange')
+ effortPipeline = node.arguments[3].getText(rendererInputAst);
+ ts.forEachChild(node, findEffortPipeline);
+}
+findEffortPipeline(rendererInputAst);
describe.each([
['applyEffort', 'persistEffort', 'effort', 'high'],
['applyFastMode', 'persistFastMode', 'fastMode', true],
] as const)('archived settings: %s', (handler, persistName, field, value) => {
- function setup(status: 'archived' | 'deleted') {
+ function setup(status: 'archived' | 'deleted', remote = true) {
const row = { status, effort: 'low', fastMode: false } as Record<string, unknown>;
const pending = new Map();
const persist = vi.fn(async () => { row[field] = value; });
- const response = {};
+ const response = remote ? {} : undefined;
const query = { from: () => query, where: () => query, limit: async () => [row] };
const getSession = vi.fn(() => { throw new Error('archived runtime must remain untouched'); });
const bindings = {
sessionId: 'archived-task', effort: 'high', enabled: true,
sessions: {}, eq: vi.fn(), getDbClient: () => ({ drizzle: { select: () => query } }),
- remoteResponse: response, [persistName]: persist, agentSwitchPending: pending,
+ remoteResponse: response, persistSessionFields: persist, agentSwitchPending: pending,
assertOwnerCurrent: vi.fn(), assertSharedTaskCurrent: { admit: vi.fn() },
markRemoteSettingPersistedInsideHandler: vi.fn(), maker: { getSession },
isUserPendingAgentSwitchIntent, projectPendingAgentSwitchIntent: (intent: unknown) => intent,
@@ -92,8 +108,9 @@ describe.each([
onPendingSwitchChanged: vi.fn() },
throwIpcError: (code: string, message: string) => { throw new Error(`[${code}] ${message}`); },
};
+ const persistAxis = new Function(...Object.keys(bindings), axisHandlers.get(persistName)!)(...Object.values(bindings));
const stagePendingUserRuntimeAxis = new Function(...Object.keys(bindings), axisHandlers.get('stagePendingUserRuntimeAxis')!)(...Object.values(bindings));
- const runBindings = { ...bindings, stagePendingUserRuntimeAxis };
+ const runBindings = { ...bindings, [persistName]: persistAxis, stagePendingUserRuntimeAxis };
const run = new Function(...Object.keys(runBindings), axisHandlers.get(handler)!)(...Object.values(runBindings));
return { run, row, persist, response, getSession, pending, changed: bindings.agentSwitchDeps.onPendingSwitchChanged };
}
@@ -148,6 +165,33 @@ describe.each([
expect(h.row).toMatchObject({ status: 'archived', effort: 'low', fastMode: false });
expect(h.getSession).not.toHaveBeenCalled();
});
+
+ it.each([false, true])('commits local Renderer changes through Main (pending intent: %s)', async hasIntent => {
+ const h = setup('archived', false);
+ if (hasIntent) h.pending.set('archived-task', { targetAgentKind: 'pi', model: 'next', effort: 'low', fastMode: false });
+ const compile = (expression: string, bindings: Record<string, unknown>) => new Function(...Object.keys(bindings),
+ ts.transpileModule(`return (${expression});`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText)(...Object.values(bindings));
+ const bindings = { sessionService: { update: h.persist }, window: { electronAPI: { maker: {
+ setEffort: h.run, setFastMode: h.run,
+ } } }, log: { warn: vi.fn() }, getStickySessionDeviceId: () => undefined, setState: vi.fn(),
+ activeModel: undefined, fastMode: false, onEffortDidChange: vi.fn() };
+ if (field === 'fastMode') await compile(fastSetter.getText(rendererStoreAst), bindings)('archived-task', true);
+ else {
+ const coordinator = createEffortChangeCoordinator();
+ await enqueueEffortChange(coordinator, 'archived-task', 'high', compile(effortPipeline, bindings));
+ await coordinator.awaitRuntimeSettled('archived-task');
+ }
+ if (hasIntent) {
+ expect(h.pending.get('archived-task')).toMatchObject({ [field]: value });
+ expect(h.persist).not.toHaveBeenCalled();
+ h.pending.clear(); // restart before send loses only the volatile selection
+ expect(h.row).toEqual({ status: 'archived', effort: 'low', fastMode: false });
+ } else {
+ expect(h.persist).toHaveBeenCalledOnce();
+ expect(h.row).toMatchObject({ [field]: value });
+ }
+ expect(h.getSession).not.toHaveBeenCalled();
+ });
});
describe('session runtime control wiring', () => {
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
index 1be3f90754..16ff9f8075 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
@@ -764,11 +764,14 @@ describe('local-db:sessions:update handler wiring', () => {
expect(h.routeLock).toHaveBeenCalledWith('codex-local', expect.any(Function));
});
- it('restores an archived task for send through the normal locked status writer and broadcast', async () => {
+ it.each([false, true])('restores and broadcasts without reacquiring a held direct-send lease (held: %s)', async routeLockHeld => {
h.sqlite!.prepare("UPDATE sessions SET status = 'archived' WHERE id = ?").run('codex-local');
- await restoreArchivedSessionForSend('codex-local');
+ // A lease is already held outside ALS by direct send. Any re-entry would
+ // deadlock; the ordinary composer still acquires this route lock once.
+ h.routeLock.mockClear();
+ await restoreArchivedSessionForSend('codex-local', { routeLockHeld });
expect(h.sqlite!.prepare('SELECT status FROM sessions WHERE id = ?').get('codex-local')).toEqual({ status: 'active' });
- expect(h.routeLock).toHaveBeenCalledWith('codex-local', expect.any(Function));
+ expect(h.routeLock).toHaveBeenCalledTimes(routeLockHeld ? 0 : 1);
expect(h.tapWindowBroadcast).toHaveBeenCalledWith('local-db:sessions:patched', expect.objectContaining({
sessionId: 'codex-local', patch: { status: 'active' },
}));
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index a8e5bdbcfb..dbbe298954 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -2171,10 +2171,13 @@ export async function updateSessionInDb(
/** Sending continues an ordinary archived task. Serialize with archive/delete and
* use the normal status writer so native projection and all clients see active. */
-export async function restoreArchivedSessionForSend(sessionId: string): Promise<void> {
+export async function restoreArchivedSessionForSend(
+ sessionId: string,
+ options: { routeLockHeld?: boolean } = {},
+): Promise<void> {
const ownerScope = captureOwnerScope();
const db = getDbClient().drizzle;
- await withSessionRouteLock(sessionId, async () => {
+ const restore = async () => {
const [row] = await db.select({
status: sessions.status, source: sessions.source, orcaRole: sessions.orcaRole,
orcaRemoteLead: sessions.orcaRemoteLead,
@@ -2185,8 +2188,10 @@ export async function restoreArchivedSessionForSend(sessionId: string): Promise<
if (row.source === 'bot' || row.orcaRole === 'worker' || row.orcaRemoteLead) {
throwIpcError('PRECONDITION_FAILED', 'Restore the managed task before continuing');
}
- await patchSessionMetaInDb(sessionId, { status: 'active' });
- });
+ await patchSessionMetaInDb(sessionId, { status: 'active' }, { routeLockHeld: true });
+ };
+ if (options.routeLockHeld) await restore();
+ else await withSessionRouteLock(sessionId, restore);
}
export async function patchSessionMetaInDb(
@@ -2196,6 +2201,7 @@ export async function patchSessionMetaInDb(
title?: string;
pinnedAt?: string | null;
},
+ options: { routeLockHeld?: boolean } = {},
): Promise<ReturnType<typeof sessionToCamel>> {
const ownerScope = captureOwnerScope();
for (const k of Object.keys(patch)) {
@@ -2253,7 +2259,7 @@ export async function patchSessionMetaInDb(
await closeSharedTaskForTask(sessionId, dbClient);
}
return sessionToCamel(row);
- });
+ }, options.routeLockHeld);
if (updated.status === 'deleted' && isOwnerScopeCurrent(ownerScope)) {
clearSessionAttention(sessionId, 'explicit');
}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.ts
index edf0b2ca5a..15cae7b693 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.ts
@@ -3,6 +3,7 @@ import ts from 'typescript';
import { describe, expect, it, vi } from 'vitest';
import { applyPendingAgentSwitchIfIdle, createPendingAgentSwitchRegistry, isUserPendingAgentSwitchIntent, type MakerSessionAgentSwitchHandlerDeps, type PendingAgentSwitchIntent } from '../sessionAgentSwitchHandler';
import { parseOrcaRemoteLead } from '../../../shared/orcaRemoteWorker';
+import { acquireSendToSessionLock, withSendToSessionLock } from '../sendToSessionLock';
// Execute the actual picker admission branches (local and agent-device), with
// everything after admission represented by applyLive. No Electron bootstrap.
@@ -52,6 +53,87 @@ const orcaIdentities = [
{ orcaRole: null, orcaRemoteLead: JSON.stringify(remoteLead) },
];
+function compile(expression: string, bindings: Record<string, unknown>) {
+ const js = ts.transpileModule(`return ${expression};`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+ return new Function(...Object.keys(bindings), js)(...Object.values(bindings));
+}
+
+// PR #6403 round 5: earlier closure tests pre-populated the intent and skipped
+// Renderer persistence. Exercise the real queue/lease and recovery boundary;
+// Renderer-to-IPC persistence is covered in the existing cross-file guard suite.
+describe('complete selection commit boundaries', () => {
+ it('reads a picker intent staged while the direct send waits for the real route lock', async () => {
+ const pending = createPendingAgentSwitchRegistry();
+ let status = 'archived';
+ let finishPicker!: () => void;
+ let pickerStarted!: () => void;
+ const started = new Promise<void>(resolve => { pickerStarted = resolve; });
+ const picker = withSendToSessionLock('queued-picker', async () => {
+ pickerStarted();
+ await new Promise<void>(resolve => { finishPicker = resolve; });
+ pending.set('queued-picker', { targetAgentKind: 'codex', model: 'new', providerId: null, sameAgentSelection: true });
+ });
+ await started;
+ const selected = vi.fn(async () => {
+ if (status !== 'active') throw new Error('archived selection applied');
+ return {};
+ });
+ const deps = { pendingSwitches: pending, getLiveSession: () => null, selectSameAgentModel: selected,
+ bootstrapSwitchedSession: vi.fn(), log: { warn: vi.fn() } } as unknown as MakerSessionAgentSwitchHandlerDeps;
+ const directSend = compile(directSendAdapter, { agentSwitchPending: pending, acquireSendToSessionLock,
+ restoreArchivedSessionForSend: async () => { status = 'active'; },
+ reconcileBotModelRoute: vi.fn(), applyPendingAgentSwitchIfIdle, isUserPendingAgentSwitchIntent,
+ agentSwitchDeps: deps, contextOverflowRolloverHolder: null });
+ const sending = directSend('queued-picker');
+ finishPicker();
+ await picker;
+ const lease = await sending;
+ try {
+ expect(status).toBe('active');
+ expect(selected).toHaveBeenCalledOnce();
+ expect(pending.get('queued-picker')).toBeUndefined();
+ let subsequentStarted = false;
+ const subsequent = withSendToSessionLock('queued-picker', async () => { subsequentStarted = true; });
+ await Promise.resolve();
+ expect(subsequentStarted).toBe(false);
+ lease.release();
+ await subsequent;
+ } finally { lease.release(); }
+ });
+
+ it.each([false, true])('retains new axes through the recovery tail (persistence fails: %s)', async fails => {
+ const pending = createPendingAgentSwitchRegistry();
+ const row = { status: 'archived', model: 'target', effort: 'low', fastMode: false };
+ const intent: PendingAgentSwitchIntent = { targetAgentKind: 'codex', model: 'target', providerId: null,
+ effort: 'low', fastMode: false, resumeFallbackRecovery: {
+ boundaryClientId: 'boundary', boundaryContent: { fromAgentKind: 'cc', toAgentKind: 'codex',
+ fromModel: 'old', toModel: 'target', fromSdkSessionId: null, handoff: 'handoff', resumed: false },
+ handoff: 'handoff', handoffClearEpoch: 0,
+ } };
+ pending.set('s1', intent);
+ const persistSessionFields = vi.fn(async (_id: string, patch: object) => {
+ if (fails) throw new Error('sqlite rejected');
+ Object.assign(row, patch);
+ });
+ const deps = { pendingSwitches: pending, getLiveSession: () => null,
+ applyResumeFallbackAtomically: vi.fn(), setPendingHandoff: vi.fn(), onPendingSwitchChanged: vi.fn(),
+ log: { warn: vi.fn() } } as unknown as MakerSessionAgentSwitchHandlerDeps;
+ const stageAxis = compile(stageAxisAdapter, { agentSwitchPending: pending, agentSwitchDeps: deps,
+ persistSessionFields, projectPendingAgentSwitchIntent: (value: unknown) => value,
+ wakeSessionInputAfterCredentialSwitch: vi.fn() });
+ if (fails) {
+ await expect(stageAxis('s1', intent, { effort: 'high', fastMode: true }, vi.fn())).rejects.toThrow('sqlite rejected');
+ expect(pending.get('s1')).toBe(intent);
+ expect(row).toMatchObject({ effort: 'low', fastMode: false });
+ } else {
+ await stageAxis('s1', intent, { effort: 'high', fastMode: true }, vi.fn());
+ await applyPendingAgentSwitchIfIdle(deps, 's1');
+ expect(pending.get('s1')).toBeUndefined();
+ expect(row).toMatchObject({ model: 'target', effort: 'high', fastMode: true });
+ }
+ });
+});
+
describe('Orca model-only picker intent admission', () => {
// PR #6403 P1: the composer already restores archived tasks, but Goal's
// direct-send lease did not. Execute the real lease, send boundary and model
@@ -126,7 +208,7 @@ describe('Orca model-only picker intent admission', () => {
const sending = directSend('s1', controller.signal);
// A later picker choice while restore awaits must be the one applied.
if (mode === 'repicked-during-restore') {
- expect(restore).toHaveBeenCalledOnce();
+ await vi.waitFor(() => expect(restore).toHaveBeenCalledOnce());
pending.set('s1', { ...intent, model: 'latest' });
finishRestore!();
}
@@ -141,7 +223,8 @@ describe('Orca model-only picker intent admission', () => {
if (mode === 'cross-engine' || mode === 'relocation') expect(row).toMatchObject({ effort: 'high', fastMode: true });
}
expect(pending.get('s1')).toBeUndefined();
- expect(restore.mock.invocationCallOrder[0]).toBeLessThan(acquire.mock.invocationCallOrder[0]);
+ expect(acquire.mock.invocationCallOrder[0]).toBeLessThan(restore.mock.invocationCallOrder[0]);
+ expect(restore).toHaveBeenCalledWith('s1', { routeLockHeld: true });
expect(release).not.toHaveBeenCalled();
lease.release();
expect(release).toHaveBeenCalledOnce();
@@ -152,7 +235,7 @@ describe('Orca model-only picker intent admission', () => {
expect(switchToDb).not.toHaveBeenCalled();
expect(pending.get('s1')).toBeDefined();
if (mode === 'cancelled') expect(restore).not.toHaveBeenCalled();
- else expect(acquire).not.toHaveBeenCalled();
+ expect(release).toHaveBeenCalledOnce();
}
});
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index d9ded32c74..a672251d98 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -10435,17 +10435,17 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
log,
});
pendingAgentSwitchApplyHolder = async (sessionId, signal, selection, beforeApply) => {
- // Match composer sends: restore before applying a user's staged model.
- // The restore owns the same route lock, so run it before acquiring the
- // direct-send lease (which is deliberately held until the caller sends).
- const pendingSelection = agentSwitchPending.get(sessionId);
- if (!signal?.aborted && isUserPendingAgentSwitchIntent(pendingSelection)) {
- await restoreArchivedSessionForSend(sessionId);
- }
let stage = 'direct-send:acquire';
let deferPendingApply = false;
const release = await acquireSendToSessionLock(sessionId, undefined, () => stage);
try {
+ // Read after acquisition: a picker can have been queued ahead of this
+ // send. Restore under this same lease through dispatch, without re-taking it.
+ const pendingSelection = agentSwitchPending.get(sessionId);
+ if (!signal?.aborted && isUserPendingAgentSwitchIntent(pendingSelection)) {
+ stage = 'direct-send:restoreArchivedSession';
+ await restoreArchivedSessionForSend(sessionId, { routeLockHeld: true });
+ }
stage = 'direct-send:reconcileBotModelRoute';
await reconcileBotModelRoute(sessionId, true);
if (beforeApply) {
@@ -22140,8 +22140,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
sessionId: string,
intent: PendingAgentSwitchIntent,
patch: Pick<PendingAgentSwitchIntent, 'effort' | 'fastMode'>,
+ assertCurrent: () => void,
) => {
const updated = { ...intent, ...patch };
+ // Recovery is a post-commit tail: its target route already owns the DB
+ // fields and the next bootstrap reads them. The tail itself only repairs
+ // the resume boundary/handoff, so it cannot consume newly staged axes.
+ if (intent.resumeFallbackRecovery) {
+ await persistSessionFields(sessionId, patch);
+ assertCurrent();
+ }
if (intent.sameAgentSelection) {
return agentSwitchDeps.selectSameAgentModel!(sessionId, updated, false);
}
@@ -22174,11 +22182,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const remoteInvoke = isDeviceLinkInvoke();
const remoteResponse = remoteInvoke ? {} : undefined;
const persistEffort = async () => {
- if (!remoteResponse) return;
assertOwnerCurrent();
assertSharedTaskCurrent.admit();
await persistSessionFields(sessionId, { effort });
- markRemoteSettingPersistedInsideHandler(remoteResponse);
+ if (remoteResponse) markRemoteSettingPersistedInsideHandler(remoteResponse);
};
const applyEffort = async () => {
const [runtimeStatus] = await getDbClient()
@@ -22200,12 +22207,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (isUserPendingAgentSwitchIntent(userIntent)) {
assertOwnerCurrent();
assertSharedTaskCurrent.admit();
- const result = await stagePendingUserRuntimeAxis(sessionId, userIntent, { effort });
+ const result = await stagePendingUserRuntimeAxis(sessionId, userIntent, { effort }, assertOwnerCurrent);
if (remoteResponse) markRemoteSettingPersistedInsideHandler(remoteResponse);
return remoteResponse ?? result;
}
if (runtimeStatus.status === 'archived') {
- // 本地由 renderer 落库,远控在此等待落库;不重建归档时清掉的 runtime 状态。
+ // Main owns both local and remote commits; Renderer must not write a
+ // target axis onto the old route while an intent is still pending.
await persistEffort();
return remoteResponse;
}
@@ -22232,8 +22240,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 有 pending 凭证切换 = 本会话的 model/effort 变更已整体延迟到 turn 结束重建:
// 跳过对仍在跑的旧 turn 的 runtime 推送(与 renderer 本地分支的 deferred 守卫同因,
// 这里是唯一 choke point,同时覆盖 device-link 远程入口;review P2 2026-07-04)。
- // 持久化不受影响:本地由 renderer sessionService.update 落盘,远程由 device-link
- // dispatch 的 persistRemoteSetting 按请求值落被控端 DB,重建时生效。
+ // 本地与设备互联均由此 handler 等待落盘,重建时再应用。
if (pendingCredentialSwitchHolder?.has(sessionId)) {
await commitRuntimeAxisAfterPersistence({
persist: persistEffort,
@@ -22244,9 +22251,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
return remoteResponse;
}
try {
- const previousProfile = remoteInvoke
- ? (await readSessionRuntimeProfiles(sessionId))?.effective
- : undefined;
+ const previousProfile = (await readSessionRuntimeProfiles(sessionId))?.effective;
const result = await applyRuntimeEffortWithRecovery({
applyRuntime: () => {
assertOwnerCurrent();
@@ -22274,7 +22279,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
persist: persistEffort,
commit: commitEffort,
assertCanCommit: assertOwnerCurrent,
- ...(remoteInvoke && result === 'applied' && previousProfile
+ ...(result === 'applied' && previousProfile
? {
recoverAfterPersistenceFailure: () =>
recoverRemoteRuntimeAxisPersistence(
@@ -22703,11 +22708,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const remoteInvoke = isDeviceLinkInvoke();
const remoteResponse = remoteInvoke ? {} : undefined;
const persistFastMode = async () => {
- if (!remoteResponse) return;
assertOwnerCurrent();
assertSharedTaskCurrent.admit();
await persistSessionFields(sessionId, { fastMode: enabled });
- markRemoteSettingPersistedInsideHandler(remoteResponse);
+ if (remoteResponse) markRemoteSettingPersistedInsideHandler(remoteResponse);
};
const applyFastMode = async () => {
const [runtimeStatus] = await getDbClient()
@@ -22729,7 +22733,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (isUserPendingAgentSwitchIntent(userIntent)) {
assertOwnerCurrent();
assertSharedTaskCurrent.admit();
- const result = await stagePendingUserRuntimeAxis(sessionId, userIntent, { fastMode: enabled });
+ const result = await stagePendingUserRuntimeAxis(sessionId, userIntent, { fastMode: enabled }, assertOwnerCurrent);
if (remoteResponse) markRemoteSettingPersistedInsideHandler(remoteResponse);
return remoteResponse ?? result;
}
@@ -22777,9 +22781,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
log.debug('set-fast-mode: skipped live push (pending credential switch)', { sessionId });
return remoteResponse;
}
- const previousProfile = remoteInvoke
- ? (await readSessionRuntimeProfiles(sessionId))?.effective
- : undefined;
+ const previousProfile = (await readSessionRuntimeProfiles(sessionId))?.effective;
assertOwnerCurrent();
assertSharedTaskCurrent.admit();
await sess.setFastMode(enabled);
@@ -22787,7 +22789,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
persist: persistFastMode,
commit: commitFastMode,
assertCanCommit: assertOwnerCurrent,
- ...(remoteInvoke && previousProfile
+ ...(previousProfile
? {
recoverAfterPersistenceFailure: () =>
recoverRemoteRuntimeAxisPersistence(
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index 16529034e1..0920746148 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -7848,13 +7848,12 @@ export function ChatInput({
);
}
} else {
- // 同一会话的 effort/model/provider 共用 commit lane,按点击顺序提交 DB → UI。
- // runtime 不阻塞 lane;旧 IPC 晚完成时 coordinator 会重放最新 effort。
+ // 同一会话共用 commit lane;Main 在 route lock 内决定合入暂存选择或
+ // 提交当前路由。Renderer 不提前把目标档位写到旧模型的 DB 行上。
await enqueueEffortChange(effortChangeCoordinatorRef.current, sessionId, newEffort, {
persist: (targetSessionId, effort) =>
- sessionService.update(targetSessionId, { effort }),
- applyRuntime: (targetSessionId, effort) =>
window.electronAPI.maker.setEffort(targetSessionId, effort),
+ applyRuntime: async () => {}, // Main has already committed the runtime and its fields.
onCommitted: (targetSessionId, effort) => {
if (activeModel)
syncSessionDraftModelPrefs(activeModel, { effort, fast: fastMode });
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index d2e039dd83..0cbc4b5a0a 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -17372,7 +17372,7 @@ function updatePendingPlanReviewContent(
*/
/**
* Toggle Fast Mode for a session.
- * Server-first: persist to DB, then update store + push to SDK via IPC.
+ * Host-first: Main owns the runtime/DB or pending-intent commit, then update UI.
*/
async function setFastMode(
sessionId: string,
@@ -17402,16 +17402,11 @@ async function setFastMode(
return;
}
try {
- await sessionService.update(sessionId, { fastMode: enabled });
+ await window.electronAPI.maker.setFastMode(sessionId, enabled);
setState(sessionId, (s) => {
if (s.fastMode === enabled) return s;
return { ...s, fastMode: enabled };
});
- // 无条件推 IPC:codex → agent setFastMode;claude-code → main 记 bridge 会话态
- // (chatgpt/ 模型经订阅 handler 的 prefs 生效),其余在 main 侧安全 no-op。
- await window.electronAPI.maker.setFastMode(sessionId, enabled).catch((err: unknown) => {
- log.warn('setFastMode IPC failed:', err);
- });
} catch (err) {
log.warn('setFastMode persist failed:', err);
throw err;
@@ -17474,7 +17469,7 @@ async function setPlanMode(sessionId: string, enabled: boolean): Promise<void> {
/**
* Reset Fast Mode to OFF.
- * Server-first: persist false to DB, then update store + push to SDK via IPC.
+ * Main owns the same commit as an explicit Fast change.
* Used when model changes automatically invalidate fast mode.
*/
async function resetFastMode(sessionId: string): Promise<void> {
@@ -17490,15 +17485,11 @@ async function resetFastMode(sessionId: string): Promise<void> {
return;
}
try {
- await sessionService.update(sessionId, { fastMode: false });
+ await window.electronAPI.maker.setFastMode(sessionId, false);
setState(sessionId, (s) => {
if (!s.fastMode) return s;
return { ...s, fastMode: false };
});
- // 与 setFastMode 同理:无条件推,main 按 agentKind / 模型分流。
- await window.electronAPI.maker.setFastMode(sessionId, false).catch((err: unknown) => {
- log.warn('resetFastMode IPC failed:', err);
- });
} catch (err) {
log.warn('resetFastMode persist failed:', err);
}
diff --git a/docs/dev-rules/model-catalog-runtime.md b/docs/dev-rules/model-catalog-runtime.md
index 36774f3748..5c4e2f0cda 100644
--- a/docs/dev-rules/model-catalog-runtime.md
+++ b/docs/dev-rules/model-catalog-runtime.md
@@ -50,11 +50,13 @@ thread 配置,同时设置窗口和 90% 自动压缩预算,保留原生 5%
### 归档任务的模型设置
归档任务允许用户调整模型、推理强度与 Fast,不要求先恢复,也不因设置变化恢复任务。
-模型选择沿用活动任务的暂存意图,下一次发送(含 Goal 直发)先经普通任务恢复入口恢复
+模型选择沿用活动任务的暂存意图,下一次发送(含 Goal 直发)在现有发送锁内读取最新意图,经普通任务恢复入口恢复
任务再应用;受管任务的恢复限制保持不变。暂存意图仍只在被控端
内存中保留,不新增跨进程恢复。已有用户模型意图时,无论同引擎、跨引擎或换执行电脑,
推理强度与 Fast 都更新完整待选意图,保留目标路由和窗口确认,不改写自动意图;否则
-只保存任务字段,不重建归档时清掉的 runtime 状态。自动模型变更与已删除任务仍拒绝。
+只保存任务字段,不重建归档时清掉的 runtime 状态。本地与远控档位均由 Main 协调提交,
+Renderer 不提前写旧路由字段;恢复尾段表示路由已提交,后续档位先保存到该目标路由,
+再更新意图展示,避免仅修复交接的尾段清意图时丢掉设置。自动模型变更与已删除任务仍拒绝。
本机桌面、设备互联与手机共用此处理,见 `maker-ipc/register.ts` 和
`sessionRuntimeControlWiring.test.ts` 与 `orcaModelSelectionIntent.test.ts` 的归档生命周期回归。