Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
perf(renderer): typing-first streaming notification cadence
Zhang Yunjin5a5004446d5e
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.tsindex cd10158499..b06068dfb9 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts@@ -97,6 +97,11 @@ import {makerChatStore,type ChatMessage,} from '@/lib/makerChatStore';+import {+ __resetComposerTypingActivityForTest,+ isComposerTypingRecently,+ markComposerTypingActivity,+} from '@/lib/composerTypingActivity';import * as messageService from '@/lib/messageService';import * as sessionService from '@/lib/sessionService';import * as sessionsBus from '@/lib/sessionsBus';@@ -585,6 +590,7 @@ describe('makerChatStore text delta batching', () => {});afterEach(() => {+ __resetComposerTypingActivityForTest();makerChatStore.__teardownGlobalListeners();makerChatStore.purgeSession(SESSION_ID);makerChatStore.__resetRemoteTerminalTombstonesForTest();@@ -743,6 +749,162 @@ describe('makerChatStore text delta batching', () => {unsubscribe();});+ it('stretches the delta notification cadence while the composer is being typed in, then restores it', () => {+ let notifyCount = 0;+ const unsubscribe = makerChatStore.subscribe(SESSION_ID, () => {+ notifyCount += 1;+ });++ markComposerTypingActivity();+ expect(isComposerTypingRecently()).toBe(true);+ emitTextDelta('a');+ vi.advanceTimersByTime(32);+ expect(notifyCount).toBe(0);++ vi.advanceTimersByTime(218);+ expect(notifyCount).toBe(1);++ emitTextDelta('b');+ vi.advanceTimersByTime(32);+ expect(notifyCount).toBe(1);+ vi.advanceTimersByTime(218);+ expect(notifyCount).toBe(2);++ // 打字信号过期后恢复 32ms 节奏。+ vi.advanceTimersByTime(1_000);+ expect(isComposerTypingRecently()).toBe(false);+ emitTextDelta('c');+ vi.advanceTimersByTime(32);+ expect(notifyCount).toBe(3);++ unsubscribe();+ });++ it('stretches the deferred high-frequency (non-text) notification cadence while the composer is being typed in', () => {+ let notifyCount = 0;+ const unsubscribe = makerChatStore.subscribe(SESSION_ID, () => {+ notifyCount += 1;+ });++ markComposerTypingActivity();+ onEvent?.({+ sessionId: SESSION_ID,+ event: {+ type: 'tool_use',+ source: 'claude-code',+ data: { toolUseId: 'tool-typing-1', toolName: 'Read', input: { file_path: 'a.ts' } },+ },+ persistId: 'tool-typing-1',+ });++ vi.advanceTimersByTime(32);+ expect(notifyCount).toBe(0);+ vi.advanceTimersByTime(218);+ expect(notifyCount).toBe(1);++ unsubscribe();+ });++ it('notifies permission interaction requests synchronously even inside the typing window', () => {+ let notifyCount = 0;+ const unsubscribe = makerChatStore.subscribe(SESSION_ID, () => {+ notifyCount += 1;+ });++ markComposerTypingActivity();+ emitTextDelta('need approval');+ emitInteractionRequest({+ kind: 'permission',+ requestId: 'perm-typing-1',+ toolName: 'Read',+ input: { file_path: 'a.ts' },+ });++ expect(notifyCount).toBeGreaterThanOrEqual(1);+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingPermission?.requestId).toBe('perm-typing-1');++ unsubscribe();+ });++ it('keeps turn start and done status frames immediate inside the typing window', () => {+ let notifyCount = 0;+ const unsubscribe = makerChatStore.subscribe(SESSION_ID, () => {+ notifyCount += 1;+ });++ markComposerTypingActivity();+ emitStatus({ status: 'Generating...', isRunning: true });+ expect(notifyCount).toBe(1);+ emitStatus({ status: 'Done', isRunning: false });+ expect(notifyCount).toBe(2);++ unsubscribe();+ });++ it('defers pure running status refresh frames through the deferred queue', () => {+ let notifyCount = 0;+ const unsubscribe = makerChatStore.subscribe(SESSION_ID, () => {+ notifyCount += 1;+ });++ emitStatus({ status: 'Generating...', isRunning: true });+ expect(notifyCount).toBe(1);++ emitStatus({ status: 'Generating...', isRunning: true, tokenUsage: 5 });+ expect(notifyCount).toBe(1);+ vi.advanceTimersByTime(32);+ expect(notifyCount).toBe(2);++ unsubscribe();+ });++ it('carries queued text into the deferred queue when a running status refresh frame arrives while typing', () => {+ let notifyCount = 0;+ const unsubscribe = makerChatStore.subscribe(SESSION_ID, () => {+ notifyCount += 1;+ });++ emitStatus({ status: 'Generating...', isRunning: true });+ expect(notifyCount).toBe(1);++ markComposerTypingActivity();+ emitTextDelta('queued ');+ emitStatus({ status: 'Generating...', isRunning: true, tokenUsage: 3 });+ expect(notifyCount).toBe(1);++ vi.advanceTimersByTime(250);+ expect(notifyCount).toBe(2);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages.map((m) => m.role)).toContain('assistant');++ unsubscribe();+ });++ it('defers running status refresh frames that carry a turnOrigin (scheduled-task turns)', () => {+ let notifyCount = 0;+ const unsubscribe = makerChatStore.subscribe(SESSION_ID, () => {+ notifyCount += 1;+ });++ const turnOrigin = { kind: 'scheduled', surface: 'im' };+ onEvent?.({+ sessionId: SESSION_ID,+ turnOrigin,+ event: { type: 'status', source: 'claude-code', data: { status: 'Generating...', isRunning: true } },+ });+ expect(notifyCount).toBe(1);++ onEvent?.({+ sessionId: SESSION_ID,+ turnOrigin,+ event: { type: 'status', source: 'claude-code', data: { status: 'Generating...', isRunning: true, tokenUsage: 7 } },+ });+ expect(notifyCount).toBe(1);+ vi.advanceTimersByTime(32);+ expect(notifyCount).toBe(2);++ unsubscribe();+ });+it('drops stale ghost pushes before they mutate the current owner slice', () => {const staleOwnerStamp = { dataOwnerId: 'owner-b', ownerGeneration: 1 };const currentOwnerStamp = { dataOwnerId: 'owner-a', ownerGeneration: 1 };diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex a78afe0bbf..16529034e1 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -73,6 +73,7 @@ import {} from './SlashCommandDecoration';import { cn } from '@/lib/utils';+import { markComposerTypingActivity } from '@/lib/composerTypingActivity';import { Spinner } from '@/components/ui/spinner';import { toast } from '@/lib/toast';import { mapIpcErrorToI18nKey } from '@/utils/ipcError';@@ -2280,6 +2281,12 @@ export function ChatInput({],editorProps: {clipboardTextSerializer: (slice) => serializeEditorSlice(editorRef.current, slice),+ // typing-first:键盘字符输入是唯一开窗入口(handleTextInput 不会在程序性+ // dispatch / 语音回填时触发);IME 组合输入在 onUpdate 里补(见该处注释)。+ handleTextInput: () => {+ markComposerTypingActivity();+ return false; // 不拦截默认插入+ },attributes: {class: cn(// py + 负 my:.ProseMirror 自身是 overflow 裁剪容器,inline 装饰@@ -2565,6 +2572,11 @@ export function ChatInput({return true;},handleKeyDown(view, event) {+ // typing-first:真实键盘的删除键与字符输入同属活跃编辑,纳入开窗;+ // 程序性删除(commands.deleteSelection 等)不走 keydown,不受影响。+ if (event.key === 'Backspace' || event.key === 'Delete') {+ markComposerTypingActivity();+ }// 首页建议预览正遮住正文时,编辑器可能仍持有焦点:先撤掉预览并吞掉这一键,// 保证编辑与发送永远作用在用户看得见的正文上。纯修饰键不算。if (@@ -2847,6 +2859,16 @@ export function ChatInput({scheduleCaretScroll(ed);return;}+ // typing-first 调度:键盘输入已在 handleTextInput 开窗;这里只补 IME 组合+ // 输入(composition 期间不触发 handleTextInput,ProseMirror 给组合事务自动+ // 带 'composition' meta)。语音回填、草稿恢复、发送后清空等程序性写入两者+ // 皆不命中,不会误开窗口。+ if (+ transaction.docChanged &&+ (ed.view.composing || transaction.getMeta('composition') === true)+ ) {+ markComposerTypingActivity();+ }// composer-draft-mount-race 修复 (issue #40):hydration 还没跑过 → 这次// onUpdate 是 Tiptap mount 期间的初始触发(空 editor),不能写 store。if (!hasHydratedRef.current) {@@ -5401,7 +5423,13 @@ export function ChatInput({return;}if (makeResult.kind === 'started' || makeResult.kind === 'preflight') {- editor.commands.clearContent(true);+ // 程序性清空不刷新打字信号(isRestoringRef 守卫),与其它 clearContent 口径一致。+ isRestoringRef.current = true;+ try {+ editor.commands.clearContent(true);+ } finally {+ isRestoringRef.current = false;+ }historyIndexRef.current = -1;hydratedHistoryDocumentRef.current = null;draftRef.current = null;diff --git a/apps/desktop/src/renderer/lib/composerTypingActivity.ts b/apps/desktop/src/renderer/lib/composerTypingActivity.tsnew file mode 100644index 0000000000..158b9637a2--- /dev/null+++ b/apps/desktop/src/renderer/lib/composerTypingActivity.ts@@ -0,0 +1,29 @@+/**+ * composerTypingActivity — 会话 composer 的「正在打字」毫秒级信号。+ *+ * 用途:多会话同时流式输出时,store 的高频通知(32ms 合并批)会让 React 在+ * 用户敲键的间隙反复重渲染重子树(CCAgentSessionView / MessageStream / 侧栏),+ * 打字延迟直接被这些渲染吃掉。makerChatStore 读这个信号把通知节奏在打字窗口+ * 内拉稀(typing-first 调度),信号过期后下一个 tick 起恢复原节奏。+ *+ * 刷新点在 ChatInput:键盘字符输入走 editorProps.handleTextInput,IME 组合+ * 输入走 onUpdate 的 composition meta(两者之外的一切程序性写入——语音回填、+ * 草稿恢复、发送后清空、按钮插入——都不开窗)。+ */++const TYPING_ACTIVITY_WINDOW_MS = 800;++let typingActivityUntil = 0;++export function markComposerTypingActivity(): void {+ typingActivityUntil = Date.now() + TYPING_ACTIVITY_WINDOW_MS;+}++export function isComposerTypingRecently(): boolean {+ return Date.now() < typingActivityUntil;+}++/** 测试专用:清掉打字窗口,避免模块级状态跨用例泄漏。 */+export function __resetComposerTypingActivityForTest(): void {+ typingActivityUntil = 0;+}diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 0440f8bcdc..f06887a59f 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -1,5 +1,6 @@import { readBotTaskResults } from '@cindy/maker-shared/botCollaboration';import { asyncQuestionNeedsSupplement, formatAsyncQuestionSupplement } from '@cindy/maker-shared/interaction';+import { isComposerTypingRecently } from './composerTypingActivity';import { readTokenSpeedSnapshot, type TokenSpeedSnapshot } from '@cindy/maker-shared/usage-format';import { remotePluginSetupErrorCode, type PluginSetupCommandError } from './pluginSetupCommandError';export type { PluginSetupCommandError } from './pluginSetupCommandError';@@ -3235,6 +3236,13 @@ const globalListeners = new Set<() => void>();// 工具事件风暴时仍同步写入权威 state,但把 React/sidebar 订阅通知压成每会话每帧一次。// Stop、terminal、interaction 等控制路径会取消该会话的待发通知并立即广播最新快照。const HIGH_FREQUENCY_NOTIFY_INTERVAL_MS = 32;+// 用户正在 composer 打字时把通知节奏拉稀:多会话同时流式输出时,32ms 批会让+// React 在按键间隙反复重渲染重子树,打字延迟被渲染吃掉。打字优先拿主线程。+// 注意:恢复不是瞬时的——最后一次按键后续窗,已排队的 tick 仍按 250ms 走完+// 当前窗口(尾部最多滞后 ~1s)才回 32ms;嫌慢可调小+// composerTypingActivity 的 TYPING_ACTIVITY_WINDOW_MS。控制路径不走这里,+// 交互卡/权限卡不受影响。+const TYPING_PRIORITY_NOTIFY_INTERVAL_MS = 250;const HIGH_FREQUENCY_NOTIFY_MAX_SESSIONS_PER_TICK = 8;const pendingDeferredStateNotifications = new Set<string>();const pendingMessageCreatedPatches = new Map<string, string>();@@ -3254,7 +3262,9 @@ function scheduleDeferredStateNotifications(): void {if (deferredStateNotificationTimer) return;deferredStateNotificationTimer = setTimeout(flushDeferredStateNotifications,- HIGH_FREQUENCY_NOTIFY_INTERVAL_MS,+ isComposerTypingRecently()+ ? TYPING_PRIORITY_NOTIFY_INTERVAL_MS+ : HIGH_FREQUENCY_NOTIFY_INTERVAL_MS,);}@@ -7638,7 +7648,13 @@ function flushAllPendingTextDeltas(): void {function scheduleTextDeltaFlush(): void {if (textDeltaFlushTimer) return;- textDeltaFlushTimer = setTimeout(flushAllPendingTextDeltas, TEXT_DELTA_BATCH_INTERVAL_MS);+ // 与 deferred state 通知同一口径:打字期间拉稀(见 TYPING_PRIORITY_NOTIFY_INTERVAL_MS)。+ textDeltaFlushTimer = setTimeout(+ flushAllPendingTextDeltas,+ isComposerTypingRecently()+ ? TYPING_PRIORITY_NOTIFY_INTERVAL_MS+ : TEXT_DELTA_BATCH_INTERVAL_MS,+ );}function enqueueTextDeltaPayload(@@ -7952,7 +7968,18 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {return;}const deferNotification = isHighFrequencyStreamEvent(event);- flushPendingTextDelta(sessionId, deferNotification);+ // status 纯刷新帧(见 status 分支的 isLiveStatusRefreshFrame)在打字窗口内也要拉稀,+ // 且它入口处的前置 flush 必须带 defer:否则 ~4Hz 的 status 帧会以立即通知把+ // 排队文本提前冲出去,绕过 text 层的 typing-first 节奏。turnOrigin 不参与判定:+ // 定时任务的整轮事件都带来源,而 isRunning=true 帧上 turnOrigin 只影响+ // handleStatusUpdate 内的 state 字段重置,与通知时机无关。+ const isLiveStatusRefreshFrame =+ event.type === 'status' &&+ (event.data as Record<string, unknown> | undefined)?.isRunning === true &&+ !isTurnContinuationBoundaryEvent(event) &&+ (event.data as Record<string, unknown> | undefined)?.skipTurnReset !== true &&+ getOrCreateState(sessionId).agentStatus.isRunning === true;+ flushPendingTextDelta(sessionId, deferNotification || isLiveStatusRefreshFrame);// session_id: 老链路是单独 IPC channel, 新链路融进 maker:event (Claude / Codex 同源)if (event.type === 'session_id') {@@ -7992,13 +8019,19 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {if (!isTurnContinuationBoundaryEvent(event) && !update.skipTurnReset && !update.isRunning) {supersedeInputProjectionRequests(sessionId, { supersedeOperations: true });}- setState(sessionId, (s) => {- const next = handleStatusUpdate(s, update);- if (isTurnContinuationBoundaryEvent(event) || update.skipTurnReset || update.isRunning) return next;- return event.turnOrigin- ? { ...next, lastStopWasIm: event.turnOrigin.surface === 'im' }- : next;- });+ // typing-first:isLiveStatusRefreshFrame 在事件入口处已算好(前置 flush 与+ // 本分支共用同一判定);turn 起止/边界帧保持立即广播。+ setState(+ sessionId,+ (s) => {+ const next = handleStatusUpdate(s, update);+ if (isTurnContinuationBoundaryEvent(event) || update.skipTurnReset || update.isRunning) return next;+ return event.turnOrigin+ ? { ...next, lastStopWasIm: event.turnOrigin.surface === 'im' }+ : next;+ },+ { deferNotification: isLiveStatusRefreshFrame },+ );scheduleWakeBridgeReconciliation(sessionId);return;}