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(desktop): keep effort state aligned with runtime (#692)

Junshan0e19d0298071
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetEffort.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetEffort.test.ts
new file mode 100644
index 0000000000..9fab018793
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetEffort.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ applyRuntimeEffortWithRecovery,
+ RuntimeControlTimeoutError,
+} from '../runtimeSetEffort.js';
+
+describe('applyRuntimeEffortWithRecovery', () => {
+ it('keeps a session whose runtime control succeeds', async () => {
+ const terminateSession = vi.fn(async () => undefined);
+
+ await expect(
+ applyRuntimeEffortWithRecovery({
+ applyRuntime: async () => undefined,
+ terminateSession,
+ }),
+ ).resolves.toBe('applied');
+ expect(terminateSession).not.toHaveBeenCalled();
+ });
+
+ it('propagates an immediate runtime rejection without terminating the session', async () => {
+ const terminateSession = vi.fn(async () => undefined);
+
+ await expect(
+ applyRuntimeEffortWithRecovery({
+ applyRuntime: async () => {
+ throw new Error('runtime rejected');
+ },
+ terminateSession,
+ }),
+ ).rejects.toThrow('runtime rejected');
+ expect(terminateSession).not.toHaveBeenCalled();
+ });
+
+ it('terminates a session whose runtime control never settles', async () => {
+ vi.useFakeTimers();
+ try {
+ const terminateSession = vi.fn(async () => undefined);
+ const result = applyRuntimeEffortWithRecovery({
+ applyRuntime: () => new Promise<void>(() => undefined),
+ terminateSession,
+ runtimeTimeoutMs: 25,
+ terminationTimeoutMs: 10,
+ });
+
+ await vi.advanceTimersByTimeAsync(25);
+ await expect(result).resolves.toBe('session-terminated');
+ expect(terminateSession).toHaveBeenCalledOnce();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('bounds a stuck recovery termination', async () => {
+ vi.useFakeTimers();
+ try {
+ const result = applyRuntimeEffortWithRecovery({
+ applyRuntime: () => new Promise<void>(() => undefined),
+ terminateSession: () => new Promise<void>(() => undefined),
+ runtimeTimeoutMs: 25,
+ terminationTimeoutMs: 10,
+ });
+ const rejection = expect(result).rejects.toBeInstanceOf(RuntimeControlTimeoutError);
+
+ await vi.advanceTimersByTimeAsync(35);
+ await rejection;
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index b28cfba9b7..a9dd4a2a7c 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -539,6 +539,7 @@ import {
isLocalSessionBusy,
} from '../maker-host/codex-credential-switch.js';
import { applyRuntimeSetModelChange } from './runtimeSetModel.js';
+import { applyRuntimeEffortWithRecovery } from './runtimeSetEffort.js';
import { PendingCredentialSwitchService } from './pendingCredentialSwitch.js';
import {
DeferredCodexRestartService,
@@ -9543,7 +9544,26 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
log.debug('set-effort: skipped live push (pending credential switch)', { sessionId });
return;
}
- await sess.setEffort(effort as 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra');
+ try {
+ const result = await applyRuntimeEffortWithRecovery({
+ applyRuntime: () =>
+ sess.setEffort(
+ effort as 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra',
+ ),
+ terminateSession: () => maker.closeSession(sessionId),
+ });
+ if (result === 'session-terminated') {
+ log.warn('set-effort: timed-out runtime session terminated for lazy rebuild', {
+ sessionId,
+ });
+ }
+ } catch (error) {
+ log.warn('set-effort runtime update failed', {
+ sessionId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ throwIpcError('INTERNAL', 'Runtime effort update failed');
+ }
});
ipcMain.handle(MAKER_INVOKE.SET_PERMISSION_MODE, async (_e, sessionId: unknown, mode: unknown) => {
diff --git a/apps/desktop/src/main/maker-ipc/runtimeSetEffort.ts b/apps/desktop/src/main/maker-ipc/runtimeSetEffort.ts
new file mode 100644
index 0000000000..2c36c1636d
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/runtimeSetEffort.ts
@@ -0,0 +1,58 @@
+export class RuntimeControlTimeoutError extends Error {
+ constructor(label: string, timeoutMs: number) {
+ super(`${label} timed out after ${timeoutMs}ms`);
+ this.name = 'RuntimeControlTimeoutError';
+ }
+}
+
+function withRuntimeControlTimeout<T>(
+ operation: Promise<T>,
+ label: string,
+ timeoutMs: number,
+): Promise<T> {
+ let timeoutId: ReturnType<typeof setTimeout> | undefined;
+ const timeout = new Promise<never>((_resolve, reject) => {
+ timeoutId = setTimeout(
+ () => reject(new RuntimeControlTimeoutError(label, timeoutMs)),
+ timeoutMs,
+ );
+ });
+ return Promise.race([operation, timeout]).finally(() => {
+ if (timeoutId !== undefined) clearTimeout(timeoutId);
+ });
+}
+
+export interface ApplyRuntimeEffortWithRecoveryInput {
+ applyRuntime: () => Promise<void>;
+ terminateSession: () => Promise<void>;
+ runtimeTimeoutMs?: number;
+ terminationTimeoutMs?: number;
+}
+
+/**
+ * Bounds a live effort mutation and retires its session before reporting recovery.
+ * A timed-out control request may still settle later, so callers must not reuse that
+ * live session; the next send recreates it from the already-persisted effort.
+ */
+export async function applyRuntimeEffortWithRecovery(
+ input: ApplyRuntimeEffortWithRecoveryInput,
+): Promise<'applied' | 'session-terminated'> {
+ const runtimeTimeoutMs = input.runtimeTimeoutMs ?? 3_500;
+ const terminationTimeoutMs = input.terminationTimeoutMs ?? 1_000;
+ try {
+ await withRuntimeControlTimeout(
+ Promise.resolve().then(input.applyRuntime),
+ 'effort runtime update',
+ runtimeTimeoutMs,
+ );
+ return 'applied';
+ } catch (error) {
+ if (!(error instanceof RuntimeControlTimeoutError)) throw error;
+ await withRuntimeControlTimeout(
+ Promise.resolve().then(input.terminateSession),
+ 'effort runtime recovery',
+ terminationTimeoutMs,
+ );
+ return 'session-terminated';
+ }
+}
diff --git a/apps/desktop/src/renderer/__tests__/effortRuntimeDirtySendGuard.test.ts b/apps/desktop/src/renderer/__tests__/effortRuntimeDirtySendGuard.test.ts
new file mode 100644
index 0000000000..90d10ff757
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/effortRuntimeDirtySendGuard.test.ts
@@ -0,0 +1,26 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+const chatInputSource = readFileSync(
+ resolve(process.cwd(), 'src/renderer/components/new-chat/ChatInput.tsx'),
+ 'utf8',
+);
+
+describe('effort runtime send guard', () => {
+ it('only locks composer mutations during the bounded effort preflight', () => {
+ expect(chatInputSource).toContain(
+ 'const composerEditorLocked = disabled || sendDispatchInFlight;',
+ );
+ expect(chatInputSource).toContain('const composerMutationLocked = composerEditorLocked || voiceInput.isBusy;');
+ expect(chatInputSource).toContain('editable: !composerEditorLocked');
+ expect(chatInputSource).toContain('if (composerMutationLockedRef.current) return true;');
+ expect(chatInputSource).toContain('if (composerMutationLocked) return;');
+ expect(chatInputSource).toContain('localAttachmentPickerEnabled && !composerMutationLocked ? addFiles : undefined');
+ expect(chatInputSource).toContain('disabled={composerMutationLocked}');
+ expect(chatInputSource).toContain('setSendDispatchInFlight(true);');
+ expect(chatInputSource).toContain('setSendDispatchInFlight(false);');
+ expect(chatInputSource).not.toContain('coordinator.markRuntimeDirty(sessionId)');
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts b/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts
index fae2b3c4e3..7f62984c08 100644
--- a/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts
+++ b/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts
@@ -301,7 +301,7 @@ describe('NewMakerDraftRoute CREATE AGENT visual contract', () => {
// 本机会话可选附件,但远程或身份尚未回流的已建会话不能摄入控制端绝对路径。
expect(chatInputSource).toContain('const localAttachmentPickerEnabled =');
expect(chatInputSource).toContain(
- 'onAddFiles={localAttachmentPickerEnabled ? addFiles : undefined}',
+ 'localAttachmentPickerEnabled && !composerMutationLocked ? addFiles : undefined',
);
expect(chatInputSource).not.toContain('(extraDirs !== undefined && onExtraDirsChange)');
expect(chatInputSource).not.toContain(
diff --git a/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts b/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts
index 8ca22733b0..8f6fc8e3ec 100644
--- a/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts
+++ b/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts
@@ -253,7 +253,9 @@ describe('OrcaWorkflowRoute source invariants', () => {
expect(chatInputSource).toContain(
"autofocus: !disableAutofocus && !disabled ? 'end' : false",
);
- expect(chatInputSource).toContain('editor?.setEditable(!disabled)');
+ // The composer is also temporarily read-only during the bounded effort-runtime
+ // preflight, so a pending send cannot clear text entered after its snapshot.
+ expect(chatInputSource).toContain('editor?.setEditable(!composerMutationLocked)');
});
it('does not block collaboration tab opening on worker SDK bootstrap', () => {
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index 14653ecdce..34ca6f3018 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -97,10 +97,14 @@ import {
type ModelMemoryAccessors,
} from './ModelSelector';
import {
- createEffortChangeCoordinator,
enqueueEffortChange,
+ getEffortChangeCoordinator,
isSessionScopeCurrent,
} from './effortChangeQueue';
+import {
+ captureComposerSendSnapshot,
+ isComposerSendSnapshotCurrent,
+} from './composerSendSnapshot';
import { useRemoteSessionConnection } from '@/features/cc-agent/hooks/useRemoteSessionConnection';
import {
@@ -1090,6 +1094,8 @@ export function ChatInput({
discardFiles,
clearFiles,
} = attachmentState;
+ const attachmentsRef = useRef(attachments);
+ attachmentsRef.current = attachments;
// browser-comment-chip:内置浏览器页面评论(结构化,不进草稿文本),渲染为
// 「N 条注释」胶囊,发送时序列化 + 截图并入 filesToSend。
const [browserComments, setBrowserComments] = useState<BrowserCommentDraftItem[]>([]);
@@ -1180,7 +1186,6 @@ export function ChatInput({
() => !!sessionId && hasPendingAgentSendDispatch(sessionId),
() => false,
);
-
useEffect(() => {
setPendingRemoteSwitch(null);
setRemoteSwitchInFlight(false);
@@ -1509,6 +1514,13 @@ export function ChatInput({
const folderOpen = folderPickerOpen ?? internalFolderOpen;
const setFolderOpen = onFolderPickerOpenChange ?? setInternalFolderOpen;
+ // `dispatchSend` 在取发送快照后可能等待 effort runtime 同步。此窗口内继续编辑会让
+ // 成功发送后的清理误删尚未发送的文字或附件,因此 composer 必须作为一个整体短暂只读。
+ // 正常路径没有等待;只有设置同步中的会话最多锁 5 秒(见 dispatchSend 的 preflight)。
+ const [sendDispatchInFlight, setSendDispatchInFlight] = useState(false);
+ const composerEditorLocked = disabled || sendDispatchInFlight;
+ const composerMutationLockedRef = useRef(composerEditorLocked);
+ composerMutationLockedRef.current = composerEditorLocked;
useEffect(() => {
setWorkingDir(initialWorkingDir ?? null);
@@ -1555,7 +1567,7 @@ export function ChatInput({
// autofocus would otherwise overwrite routed Plugin/Create end-focus.
// doc 模式下必须关掉,理由见上方 disableAutofocus prop 注释。
autofocus: !disableAutofocus && !disabled ? 'end' : false,
- editable: !disabled,
+ editable: !composerEditorLocked,
extensions: [
Document,
Paragraph,
@@ -1652,6 +1664,7 @@ export function ChatInput({
return false;
},
handlePaste(view, event) {
+ if (composerMutationLockedRef.current) return true;
// Intercept clipboard file/folder/image. Three sources to handle,
// matching the onDrop logic below:
// 1. Folder copied from OS file manager → addFolderPath (@dir chip)
@@ -2222,10 +2235,6 @@ export function ChatInput({
[editor],
);
- useEffect(() => {
- editor?.setEditable(!disabled);
- }, [disabled, editor]);
-
// Hold a live ref to the editor for handlers that mount before Tiptap
// exposes it through React (e.g. the blur handler above).
const editorRef = useRef<Editor | null>(null);
@@ -2382,6 +2391,11 @@ export function ChatInput({
);
const voiceInput = useVoiceInput(editor, disabled, messages, voiceInputOptions);
+ const composerMutationLocked = composerEditorLocked || voiceInput.isBusy;
+ composerMutationLockedRef.current = composerMutationLocked;
+ useEffect(() => {
+ editor?.setEditable(!composerMutationLocked);
+ }, [composerMutationLocked, editor]);
const { settings: voiceInputSettings } = useVoiceInputSettings();
const voiceInputShortcutLabel = useMemo(
() => formatVoiceInputShortcut(voiceInputSettings.shortcut),
@@ -2431,7 +2445,7 @@ export function ChatInput({
const voiceInputCanStopAndSendRef = useRef(false);
const composerCanSubmitRef = useRef(false);
const handleVoiceInputStartRef = useRef(handleVoiceInputStart);
- const disabledRef = useRef(disabled);
+ const disabledRef = useRef(composerMutationLocked);
const disableAutofocusRef = useRef(disableAutofocus);
const focusOnStorageKeyChangeRef = useRef(focusOnStorageKeyChange);
const latestStorageKeyRef = useRef<string | undefined>(storageKey);
@@ -2459,11 +2473,11 @@ export function ChatInput({
voiceInputStopRef.current = handleVoiceInputStopWithRefinement;
voiceInputCancelRef.current = voiceInput.cancel;
handleVoiceInputStartRef.current = handleVoiceInputStart;
- disabledRef.current = disabled;
+ disabledRef.current = composerMutationLocked;
disableAutofocusRef.current = disableAutofocus;
focusOnStorageKeyChangeRef.current = focusOnStorageKeyChange;
}, [
- disabled,
+ composerMutationLocked,
disableAutofocus,
focusOnStorageKeyChange,
handleVoiceInputStart,
@@ -2752,19 +2766,6 @@ export function ChatInput({
});
}, []);
- useEffect(() => {
- if (!editor) return;
- const nextEditable = !voiceInput.isBusy;
- if (editor.isEditable !== nextEditable) {
- editor.setEditable(nextEditable, false);
- }
- return () => {
- if (!editor.isDestroyed && !editor.isEditable) {
- editor.setEditable(true, false);
- }
- };
- }, [editor, voiceInput.isBusy]);
-
// While dictation holds the editor read-only the native caret disappears;
// the decoration renders a mic-shaped caret at the insertion point instead
// (listening = animated level bars, submitting/refining = spinner).
@@ -3553,8 +3554,6 @@ export function ChatInput({
// ── Send / Stop wiring ─────────────────────────────────────────────
const dispatchSendInFlightRef = useRef(false);
- const [localSendDispatchInFlight, setSendDispatchInFlight] = useState(false);
- const sendDispatchInFlight = localSendDispatchInFlight || agentSendDispatchInFlight;
const dispatchSendRef = useRef<(deliveryMode?: MessageDeliveryMode) => void | Promise<void>>(
() => {},
);
@@ -3573,7 +3572,6 @@ export function ChatInput({
if (!finishAgentSendDispatch) return;
draftSaveSchedulerRef.current?.flush();
dispatchSendInFlightRef.current = true;
- setSendDispatchInFlight(true);
try {
await resolveSessionMessageReferencesForSend(editor);
// 引用 chip 水合会跨 device-link await;等待期间若旧客户端 / 其他入口登记了切换,
@@ -3679,6 +3677,11 @@ export function ChatInput({
? findGhostByCommand(eligibleGhosts, ghostCommandWord)
: null;
const textToSend = expandGhostCommand(text, eligibleGhosts);
+ const sendSnapshot = captureComposerSendSnapshot(
+ editor.getJSON(),
+ attachmentsRef.current,
+ browserCommentsRef.current,
+ );
let recentUsageMarked = false;
const markRecentPluginUsage = () => {
if (!usedGhost || recentUsageMarked) return;
@@ -3690,14 +3693,48 @@ export function ChatInput({
);
});
};
- dispatchSendInFlightRef.current = true;
- setSendDispatchInFlight(true);
let result: boolean | void;
+ let effortForSend = activeEffort;
try {
+ if (sessionId) {
+ const coordinator = effortChangeCoordinatorRef.current;
+ let runtimeSettled = false;
+ let timeoutId: ReturnType<typeof setTimeout> | undefined;
+ setSendDispatchInFlight(true);
+ try {
+ await Promise.race([
+ coordinator.awaitRuntimeSettled(sessionId).then(() => {
+ runtimeSettled = true;
+ }),
+ new Promise<void>((resolve) => {
+ timeoutId = setTimeout(resolve, 5000);
+ }),
+ ]);
+ } finally {
+ if (timeoutId !== undefined) clearTimeout(timeoutId);
+ setSendDispatchInFlight(false);
+ }
+
+ // 不把 timeout 写成全局 dirty:若迟到的是「持久化失败、runtime 尚未触碰」,旧实现
+ // 会永久阻断后续发送。当前这次发送直接失败;下一次会重新等待真实 settle 结果。
+ if (!runtimeSettled) {
+ toast.error(t('newChat.chatInput.effortRuntimeDirty'));
+ return;
+ }
+ // 路由切换后复用的编辑器不能把 A 会话的内容送进 B,也不能清掉 B 的草稿。
+ if (!isSessionScopeCurrent(sessionId, currentSessionIdRef.current)) return;
+ if (coordinator.isRuntimeDirty(sessionId)) {
+ toast.error(t('newChat.chatInput.effortRuntimeDirty'));
+ return;
+ }
+ // 等待 commit 后,闭包里的 activeEffort 可能仍是旧 props;以该 session 已提交的
+ // 选择发送,保证本 turn 与 UI/SQLite 的 effort 相同。
+ effortForSend = coordinator.getCommittedEffort(sessionId) ?? activeEffort;
+ }
result = await onSend(
textToSend,
activeModel,
- activeEffort,
+ effortForSend,
activePermissionMode,
filesToSend,
mentionsToSend,
@@ -3714,12 +3751,22 @@ export function ChatInput({
} catch (error) {
log.warn('send rejected:', error instanceof Error ? error.message : String(error));
return;
- } finally {
- dispatchSendInFlightRef.current = false;
- setSendDispatchInFlight(false);
}
if (result === false) return;
markRecentPluginUsage();
+ // onSend may wait on auth, commands, a remote device, or attachment work.
+ // Only clear the exact accepted snapshot; if the user changed anything
+ // after dispatch, preserve the whole current draft so no unsent work is lost.
+ if (
+ !isComposerSendSnapshotCurrent(
+ sendSnapshot,
+ editor.getJSON(),
+ attachmentsRef.current,
+ browserCommentsRef.current,
+ )
+ ) {
+ return;
+ }
// Suppress onUpdate's draft-save during the post-send clearContent so
// we don't write a transient empty-doc entry that we're about to drop.
isRestoringRef.current = true;
@@ -3741,7 +3788,6 @@ export function ChatInput({
}
} finally {
dispatchSendInFlightRef.current = false;
- setSendDispatchInFlight(false);
finishAgentSendDispatch();
}
},
@@ -3768,6 +3814,7 @@ export function ChatInput({
remoteModelListStatus,
confirmDialog,
navigate,
+ sessionId,
],
);
useEffect(() => {
@@ -3835,7 +3882,7 @@ export function ChatInput({
// 跨实例 / 跨重启的持久化由调用方通过 rememberedEffortByModel + onRememberedEffortChange
// 注入 (NewMakerDraftRoute 走 newMakerDraft store)。
const effortByModelRef = useRef<Map<string, Effort>>(new Map());
- const effortChangeCoordinatorRef = useRef(createEffortChangeCoordinator());
+ const effortChangeCoordinatorRef = useRef(getEffortChangeCoordinator());
const localRuntimeSwitchSeqBySessionRef = useRef(new Map<string, number>());
useLayoutEffect(() => {
@@ -5222,7 +5269,7 @@ export function ChatInput({
root gap-4,让 chip 与输入框间距接近 GoalIndicator 的节奏。 */}
{planModeEntry && planModeEnabled && (
<div className="-mb-2 w-full">
- <PlanModeIndicator onExit={() => void onPlanModeChange?.(false)} disabled={disabled} />
+ <PlanModeIndicator onExit={() => void onPlanModeChange?.(false)} disabled={composerMutationLocked} />
</div>
)}
{/* Voice-input error + attachment rejections (oversize / blocked /
@@ -5392,6 +5439,7 @@ export function ChatInput({
e.stopPropagation();
dragCounterRef.current = 0;
setIsDragOver(false);
+ if (composerMutationLocked) return;
onComposerDropHandled?.();
// .cindy / .cshare 已被窗口级 capture 接管(装入 / 导入链路),
// 这里只清理拖拽 UI 状态,不当附件消费。
@@ -5558,8 +5606,8 @@ export function ChatInput({
{hasAttachments && (
<ThumbnailStrip
attachments={attachments}
- onRemove={removeFile}
- onUpdate={updateFile}
+ onRemove={composerMutationLocked ? () => undefined : removeFile}
+ onUpdate={composerMutationLocked ? () => undefined : updateFile}
/>
)}
@@ -5575,7 +5623,7 @@ export function ChatInput({
className={cn(
'w-[calc(100%+11px)] -mr-[11px]',
// Disabled gets the same visual cue as the old textarea
- disabled && 'cursor-not-allowed opacity-60',
+ composerMutationLocked && 'cursor-not-allowed opacity-60',
voiceInput.isBusy && 'cursor-default',
)}
data-voice-draft-active={voiceInput.draftText ? 'true' : undefined}
@@ -5641,7 +5689,9 @@ export function ChatInput({
<ExtraDirsButton
extraDirs={extraDirs ?? []}
workingDir={workingDir}
- onAddFiles={localAttachmentPickerEnabled ? addFiles : undefined}
+ onAddFiles={
+ localAttachmentPickerEnabled && !composerMutationLocked ? addFiles : undefined
+ }
planMode={planModeEntry}
collaboration={collaboration}
plugins={pluginsForMenu}
@@ -5664,7 +5714,7 @@ export function ChatInput({
}
: undefined
}
- disabled={disabled}
+ disabled={composerMutationLocked}
dense={effectiveDenseToolbar}
visualVariant={isCreateAgentVariant ? 'create-agent' : 'default'}
/>
@@ -5673,7 +5723,7 @@ export function ChatInput({
onPermissionModeChange={handlePermissionModeChange}
vendorKey={vendorKey}
deviceId={deviceLinkDeviceId}
- disabled={disabled}
+ disabled={composerMutationLocked}
dense={effectiveDenseToolbar}
iconOnly={useUltraCompactToolbar}
visualVariant={isCreateAgentVariant ? 'create-agent' : 'default'}
@@ -5780,7 +5830,7 @@ export function ChatInput({
)}
<VoiceInputButton
state={voiceInput.state}
- disabled={!!disabled || !editor}
+ disabled={composerMutationLocked || !editor}
shortcutLabel={voiceInputShortcutLabel}
onStart={handleVoiceInputStart}
onStop={handleVoiceInputPlainStop}
diff --git a/apps/desktop/src/renderer/components/new-chat/__tests__/composerSendSnapshot.test.ts b/apps/desktop/src/renderer/components/new-chat/__tests__/composerSendSnapshot.test.ts
new file mode 100644
index 0000000000..b0757d51ac
--- /dev/null
+++ b/apps/desktop/src/renderer/components/new-chat/__tests__/composerSendSnapshot.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ captureComposerSendSnapshot,
+ isComposerSendSnapshotCurrent,
+} from '../composerSendSnapshot';
+
+const document = { type: 'doc', content: [{ type: 'paragraph' }] };
+const attachment = {
+ id: 'file-1',
+ name: 'one.txt',
+ path: '/tmp/one.txt',
+ ext: 'txt',
+ size: 3,
+ category: 'document' as const,
+};
+const comment = {
+ id: 'comment-1',
+ markerNumber: 1,
+ comment: 'keep this',
+ selector: { type: 'element' as const, value: '#one' },
+ screenshot: attachment,
+};
+
+describe('composer send snapshot', () => {
+ it('accepts unchanged editor and object versions', () => {
+ const attachments = [attachment];
+ const comments = [comment];
+ const snapshot = captureComposerSendSnapshot(document, attachments, comments);
+
+ expect(
+ isComposerSendSnapshotCurrent(snapshot, structuredClone(document), attachments, comments),
+ ).toBe(true);
+ });
+
+ it('changes when text, attachments, or comments change during send', () => {
+ const attachments = [attachment];
+ const comments = [comment];
+ const snapshot = captureComposerSendSnapshot(document, attachments, comments);
+
+ expect(
+ isComposerSendSnapshotCurrent(
+ snapshot,
+ {
+ type: 'doc',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'new' }] }],
+ },
+ attachments,
+ comments,
+ ),
+ ).toBe(false);
+ expect(
+ isComposerSendSnapshotCurrent(
+ snapshot,
+ document,
+ [attachment, { ...attachment, id: 'file-2' }],
+ comments,
+ ),
+ ).toBe(false);
+ expect(
+ isComposerSendSnapshotCurrent(
+ snapshot,
+ document,
+ attachments,
+ [{ ...comment, comment: 'new' }],
+ ),
+ ).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/renderer/components/new-chat/__tests__/effortChangeQueue.test.ts b/apps/desktop/src/renderer/components/new-chat/__tests__/effortChangeQueue.test.ts
index 3a8b94b5fe..87c4cb2987 100644
--- a/apps/desktop/src/renderer/components/new-chat/__tests__/effortChangeQueue.test.ts
+++ b/apps/desktop/src/renderer/components/new-chat/__tests__/effortChangeQueue.test.ts
@@ -4,6 +4,7 @@ import type { Effort } from '@/lib/userPreferences.types';
import {
createEffortChangeCoordinator,
enqueueEffortChange,
+ getEffortChangeCoordinator,
isSessionScopeCurrent,
} from '../effortChangeQueue';
@@ -346,4 +347,79 @@ describe('effort change coordinator', () => {
expect(remoteSwitchInFlight).toBe(false);
});
+
+ it('发送 preflight 会先等待已排队的持久化,再等待 runtime 投影', async () => {
+ const coordinator = createEffortChangeCoordinator();
+ const persistGate = deferred();
+ const runtimeGate = deferred();
+ const write = enqueueEffortChange(coordinator, 'session-a', 'xhigh', {
+ persist: async () => persistGate.promise,
+ applyRuntime: async () => runtimeGate.promise,
+ onCommitted: () => undefined,
+ });
+ let settled = false;
+ const preflight = coordinator.awaitRuntimeSettled('session-a').then(() => {
+ settled = true;
+ });
+
+ await Promise.resolve();
+ expect(settled).toBe(false);
+ persistGate.resolve();
+ await write;
+ await Promise.resolve();
+ expect(settled).toBe(false);
+ runtimeGate.resolve();
+ await preflight;
+ expect(settled).toBe(true);
+ });
+
+ it('发送 preflight 不会遗漏旧请求迟到触发的最新档位重放', async () => {
+ const coordinator = createEffortChangeCoordinator();
+ const attempts: Array<{ effort: Effort; gate: ReturnType<typeof deferred> }> = [];
+ const applyRuntime = vi.fn((_sessionId: string, effort: Effort) => {
+ const gate = deferred();
+ attempts.push({ effort, gate });
+ return gate.promise;
+ });
+
+ coordinator.publishRuntimeEffort('session-a', 'high', applyRuntime);
+ coordinator.publishRuntimeEffort('session-a', 'xhigh', applyRuntime);
+ const preflight = coordinator.awaitRuntimeSettled('session-a');
+
+ attempts[1].gate.resolve();
+ await Promise.resolve();
+ attempts[0].gate.resolve();
+ await vi.waitFor(() => expect(attempts).toHaveLength(3));
+ let settled = false;
+ void preflight.then(() => {
+ settled = true;
+ });
+ await Promise.resolve();
+ expect(settled).toBe(false);
+ expect(attempts[2].effort).toBe('xhigh');
+ attempts[2].gate.resolve();
+ await preflight;
+ });
+
+ it('runtime 拒绝由 dirty 状态承接,不让等待链抛出通用错误', async () => {
+ const coordinator = createEffortChangeCoordinator();
+ coordinator.publishRuntimeEffort('session-a', 'high', async () => {
+ throw new Error('runtime failed');
+ });
+
+ await expect(coordinator.awaitRuntimeSettled('session-a')).resolves.toBeUndefined();
+ expect(coordinator.isRuntimeDirty('session-a')).toBe(true);
+ });
+
+ it('共享协调器在 ChatInput remount 后仍保留真实 runtime 失败标记', async () => {
+ const firstMount = getEffortChangeCoordinator();
+ firstMount.publishRuntimeEffort('session-remount', 'high', async () => {
+ throw new Error('runtime failed');
+ });
+ await vi.waitFor(() => expect(firstMount.isRuntimeDirty('session-remount')).toBe(true));
+
+ const secondMount = getEffortChangeCoordinator();
+ expect(secondMount.isRuntimeDirty('session-remount')).toBe(true);
+ secondMount.suppressRuntimeEffort('session-remount');
+ });
});
diff --git a/apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts b/apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts
new file mode 100644
index 0000000000..e1dd7fb1cd
--- /dev/null
+++ b/apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts
@@ -0,0 +1,38 @@
+import type { JSONContent } from '@tiptap/core';
+
+import type { BrowserCommentDraftItem } from '@/lib/browserComments';
+import type { AttachedFile } from '@/lib/fileTypes';
+
+export interface ComposerSendSnapshot {
+ documentToken: string;
+ attachments: readonly AttachedFile[];
+ browserComments: readonly BrowserCommentDraftItem[];
+}
+
+/** Captures object versions without serializing potentially large attachment bytes. */
+export function captureComposerSendSnapshot(
+ document: JSONContent,
+ attachments: AttachedFile[],
+ browserComments: BrowserCommentDraftItem[],
+): ComposerSendSnapshot {
+ return {
+ documentToken: JSON.stringify(document),
+ attachments,
+ browserComments,
+ };
+}
+
+export function isComposerSendSnapshotCurrent(
+ snapshot: ComposerSendSnapshot,
+ document: JSONContent,
+ attachments: AttachedFile[],
+ browserComments: BrowserCommentDraftItem[],
+): boolean {
+ return (
+ snapshot.documentToken === JSON.stringify(document) &&
+ snapshot.attachments.length === attachments.length &&
+ snapshot.attachments.every((item, index) => item === attachments[index]) &&
+ snapshot.browserComments.length === browserComments.length &&
+ snapshot.browserComments.every((item, index) => item === browserComments[index])
+ );
+}
diff --git a/apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts b/apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts
index 209d0b26fd..e80ef6b972 100644
--- a/apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts
+++ b/apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts
@@ -22,6 +22,10 @@ export interface EffortChangeCoordinator {
adoptExternalEffort(sessionId: string, effort: Effort, applyRuntime: ApplyRuntimeEffort): void;
publishRuntimeEffort(sessionId: string, effort: Effort, applyRuntime: ApplyRuntimeEffort): void;
suppressRuntimeEffort(sessionId: string): void;
+ /** runtime 同步失败:用户选择已持久化,但引擎实际档位未追上。 */
+ isRuntimeDirty(sessionId: string): boolean;
+ /** 等待排队中的持久化和所有 runtime 投影都稳定下来。 */
+ awaitRuntimeSettled(sessionId: string): Promise<void>;
}
export interface EffortChangePipeline {
@@ -40,15 +44,24 @@ interface SessionLane {
committedEffort?: Effort;
runtimeRevision: number;
latestRuntimeTarget?: RuntimeTarget;
+ runtimeDirty: boolean;
+ runtimeAttempts: Set<Promise<void>>;
}
function createSessionLane(): SessionLane {
return {
commitTail: Promise.resolve(),
runtimeRevision: 0,
+ runtimeDirty: false,
+ runtimeAttempts: new Set(),
};
}
+function trackRuntimeAttempt(lane: SessionLane, attempt: Promise<void>): void {
+ lane.runtimeAttempts.add(attempt);
+ void attempt.finally(() => lane.runtimeAttempts.delete(attempt));
+}
+
function startRuntimeAttempt(
lane: SessionLane,
sessionId: string,
@@ -59,18 +72,27 @@ function startRuntimeAttempt(
try {
attempt = target.applyRuntime(sessionId, target.effort);
} catch {
+ // 会话不存在和 deferred credential switch 都会正常返回。只有真正的 runtime
+ // 控制调用失败才会走到这里;保留已持久化的用户选择,发送侧再明确阻止旧 runtime。
+ if (revision === lane.runtimeRevision) lane.runtimeDirty = true;
return;
}
- void attempt.then(
+ const settled = attempt.then(
() => {
- if (revision === lane.runtimeRevision) return;
+ if (revision === lane.runtimeRevision) {
+ lane.runtimeDirty = false;
+ return;
+ }
const latestTarget = lane.latestRuntimeTarget;
if (!latestTarget) return;
startRuntimeAttempt(lane, sessionId, lane.runtimeRevision, latestTarget);
},
- () => undefined,
+ () => {
+ if (revision === lane.runtimeRevision) lane.runtimeDirty = true;
+ },
);
+ trackRuntimeAttempt(lane, settled);
}
export function createEffortChangeCoordinator(): EffortChangeCoordinator {
@@ -104,6 +126,7 @@ export function createEffortChangeCoordinator(): EffortChangeCoordinator {
const lane = getLane(sessionId);
if (lane.committedEffort === effort) return;
lane.committedEffort = effort;
+ lane.runtimeDirty = false;
// 首次 props 水合不主动触碰 runtime;只有本组件曾发布过 runtime 目标时,
// 外部 SSoT 更新才需要抢占旧 attempt,并立即投影以覆盖 adoption 前的迟到完成。
@@ -116,6 +139,7 @@ export function createEffortChangeCoordinator(): EffortChangeCoordinator {
publishRuntimeEffort(sessionId, effort, applyRuntime) {
const lane = getLane(sessionId);
lane.runtimeRevision += 1;
+ lane.runtimeDirty = false;
const target = { effort, applyRuntime };
lane.latestRuntimeTarget = target;
startRuntimeAttempt(lane, sessionId, lane.runtimeRevision, target);
@@ -124,10 +148,36 @@ export function createEffortChangeCoordinator(): EffortChangeCoordinator {
const lane = getLane(sessionId);
lane.runtimeRevision += 1;
lane.latestRuntimeTarget = undefined;
+ lane.runtimeDirty = false;
+ },
+ isRuntimeDirty(sessionId) {
+ return getLane(sessionId).runtimeDirty;
+ },
+ async awaitRuntimeSettled(sessionId) {
+ const lane = getLane(sessionId);
+ // commit 会在 runtime 任务入队前完成;先等待它,覆盖“刚改档位就发送”的窗口。
+ // 每次 snapshot 后复查,确保迟到调用触发的重放也已经落定,而不是人为设次数上限。
+ for (;;) {
+ const commitTail = lane.commitTail;
+ await commitTail;
+ const runtimeAttempts = [...lane.runtimeAttempts];
+ // runtime failure is represented by runtimeDirty and must be handled by the
+ // caller's dedicated toast path, not leak as a generic dispatch rejection.
+ if (runtimeAttempts.length > 0) await Promise.allSettled(runtimeAttempts);
+ if (commitTail === lane.commitTail && lane.runtimeAttempts.size === 0) return;
+ }
},
};
}
+// ChatInput 会随路由卸载,但 Main 进程中的 Agent session 不会。把协调状态放在模块单例中,
+// 才不会因离开再返回会话而忘记一次尚未恢复的 runtime 同步失败。
+const sharedEffortChangeCoordinator = createEffortChangeCoordinator();
+
+export function getEffortChangeCoordinator(): EffortChangeCoordinator {
+ return sharedEffortChangeCoordinator;
+}
+
export function enqueueEffortChange(
coordinator: EffortChangeCoordinator,
sessionId: string,
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 8363a61090..9b476bb6a5 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -5234,6 +5234,7 @@
"dismiss": "Dismiss"
},
"credentialSwitchDeferred": "Model provider switched — it takes effect after the current task finishes.",
+ "effortRuntimeDirty": "Reasoning effort is still updating. Wait a moment, then send again.",
"credentialSwitchApplied": "Model provider switch is now in effect.",
"modelSwitchContextGuard": {
"title": "Target model has a smaller context window",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 3a51e2360f..2d0be8cd46 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -5232,6 +5232,7 @@
"dismiss": "閉じる"
},
"credentialSwitchDeferred": "モデルプロバイダーを切り替えました。現在のタスク終了後に有効になります。",
+ "effortRuntimeDirty": "推論強度を更新しています。少し待ってからもう一度送信してください。",
"credentialSwitchApplied": "モデルプロバイダーの切り替えが有効になりました。",
"modelSwitchContextGuard": {
"title": "切替先モデルのコンテキストウィンドウが小さいです",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 7e44510942..0ff4779313 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -5232,6 +5232,7 @@
"dismiss": "닫기"
},
"credentialSwitchDeferred": "모델 제공자를 전환했습니다. 현재 작업이 끝난 후 적용됩니다.",
+ "effortRuntimeDirty": "추론 강도를 업데이트하고 있습니다. 잠시 후 다시 전송해 주세요.",
"credentialSwitchApplied": "모델 제공자 전환이 적용되었습니다.",
"modelSwitchContextGuard": {
"title": "대상 모델의 컨텍스트 창이 더 작습니다",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 5bb028f0c9..4b9254db8c 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -5232,6 +5232,7 @@
"dismiss": "关闭"
},
"credentialSwitchDeferred": "模型来源已切换,将在当前任务结束后生效。",
+ "effortRuntimeDirty": "推理强度还在更新,稍等一下再发送",
"credentialSwitchApplied": "模型来源切换已生效。",
"modelSwitchContextGuard": {
"title": "目标模型的上下文窗口较小",