Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(agent): align response speed with tool and completion boundaries
zqchris28bf872aad0a
diff --git a/apps/desktop/src/renderer/__tests__/runningStatusBarSuppression.test.tsx b/apps/desktop/src/renderer/__tests__/runningStatusBarSuppression.test.tsxindex 047997ccce..9e72f30a56 100644--- a/apps/desktop/src/renderer/__tests__/runningStatusBarSuppression.test.tsx+++ b/apps/desktop/src/renderer/__tests__/runningStatusBarSuppression.test.tsx@@ -17,7 +17,9 @@ import {resolveRunningUsageMeta,} from '@/features/cc-agent/lib/runningTokenUsage';-vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('react-i18next', () => ({ useTranslation: () => ({+ t: (key: string, values?: { value?: unknown; rate?: unknown }) => `${key}${values?.value ?? values?.rate ?? ''}`,+}) }));// Execute the actual status bar without loading the entire session view's IPC/store graph.const source = readFileSync(@@ -46,7 +48,9 @@ const deps = {useEffect,useRef,useState,- useTranslation: () => ({ t: (key: string) => key }),+ useTranslation: () => ({+ t: (key: string, values?: { value?: unknown; rate?: unknown }) => `${key}${values?.value ?? values?.rate ?? ''}`,+ }),useReducedMotion: () => true,useAnimatedNumber: (value: number) => value,localizeAgentStatus: (status: string) => status,@@ -80,11 +84,31 @@ const RunningStatusBar = new Function(tokenUsage: number;outputTokens: number;generationDurationMs: number;+ generationActive?: boolean;generationReliable?: boolean;}>;afterEach(cleanup);+it('clears an older host recent interval immediately when native generation pauses, keeping history', () => {+ const props = { visible: true, status: 'Generating...', startedAt: Date.now(), tokenUsage: 0,+ outputTokens: 0, generationDurationMs: 0, generationReliable: true, generationActive: true };+ const view = render(<RunningStatusBar {...props} />);+ const measured = { ...props, outputTokens: 370, generationDurationMs: 1000 };+ view.rerender(<RunningStatusBar {...measured} />);+ const trigger = () => view.container.querySelector('[data-running-status-meta] button')!;+ expect(trigger().textContent).toContain('chat.runningStatus.tokenRate');+ fireEvent.click(trigger());+ view.rerender(<RunningStatusBar {...measured} generationActive={false} status="Running bash…" />);+ expect(trigger().textContent).not.toContain('chat.runningStatus.tokenRate');+ expect(screen.getByRole('dialog').textContent).toContain('370');+ expect(screen.getByRole('dialog').textContent).toContain('chat.runningStatus.observedPeak');+ view.rerender(<RunningStatusBar {...measured} generationActive />);+ expect(trigger().textContent).not.toContain('chat.runningStatus.tokenRate');+ view.rerender(<RunningStatusBar {...measured} generationActive outputTokens={470} generationDurationMs={2000} />);+ expect(trigger().textContent).toContain('chat.runningStatus.tokenRate');+});+it.each([false, true])('reconnect hides stale speed and pinned history, then waits for fresh samples (pinned=%s)', (pinned) => {const props = {visible: true, status: 'Generating...', startedAt: 1, tokenUsage: 1000,diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex 52daeba17e..27026663ea 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -5120,6 +5120,7 @@ export function CCAgentSessionView({outputTokens={agentStatus.outputTokens ?? 0}responseSpeed={agentStatus.responseSpeed}generationDurationMs={agentStatus.generationDurationMs ?? 0}+ generationActive={agentStatus.generationActive}generationReliable={agentStatus.generationReliable ?? true}startedAt={agentStatus.startedAt}visible={composerRuntimeVisible || (!pendingPlanReview && activeReconnect !== null)}@@ -5996,6 +5997,7 @@ function RunningStatusBar({outputTokens = 0,responseSpeed,generationDurationMs = 0,+ generationActive,generationReliable = true,startedAt,visible,@@ -6018,6 +6020,7 @@ function RunningStatusBar({outputTokens?: number;responseSpeed?: ResponseSpeedSnapshot;generationDurationMs?: number;+ generationActive?: boolean;generationReliable?: boolean;startedAt: number | null;visible: boolean;@@ -6192,6 +6195,7 @@ function RunningStatusBar({});const rateHistory = useRunningTokenRateHistory({responseSpeed,+ generationActive,sessionKey,startedAt,outputTokens,@@ -6203,7 +6207,7 @@ function RunningStatusBar({!backgroundTasksRunning &&!workflowWaiting,});- const latestRate = rateHistory.latestRate;+ const latestRate = !responseSpeed && generationActive === false ? null : rateHistory.latestRate;const legacyUsageMeta = resolveRunningUsageMeta({outputTokens,generationDurationMs,@@ -6329,7 +6333,7 @@ function RunningStatusBar({isTokenCount={usageMeta.kind === 'tokens'}averageRate={usageMeta.kind === 'rate' ? usageMeta.rate : null}outputTokens={responseSpeed?.outputTokens ?? outputTokens}- history={rateHistory}+ history={latestRate === rateHistory.latestRate ? rateHistory : { ...rateHistory, latestRate }}onPinnedChange={setRatePanelPinned}/>)}diff --git a/apps/desktop/src/renderer/features/cc-agent/RunningTokenRatePopover.tsx b/apps/desktop/src/renderer/features/cc-agent/RunningTokenRatePopover.tsxindex 23c7ecd5f7..3b7bad6414 100644--- a/apps/desktop/src/renderer/features/cc-agent/RunningTokenRatePopover.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/RunningTokenRatePopover.tsx@@ -23,8 +23,9 @@ export function useRunningTokenRateHistory(input: {outputTokens: number;generationDurationMs: number;generationReliable: boolean;+ generationActive?: boolean;}) {- const { sessionKey, startedAt, outputTokens, generationDurationMs, generationReliable } = input;+ const { sessionKey, startedAt, outputTokens, generationDurationMs, generationReliable, generationActive } = input;// 挂载时从按会话的进程内缓存播种:RunningStatusBar 以 sessionId 为 key,// 切走再切回是全新挂载,历史从缓存恢复而不是从零开始。const [history, setHistory] = useState<RateHistory>(() => {@@ -35,15 +36,16 @@ export function useRunningTokenRateHistory(input: {return startedAt === null ? { ...cached, baseline: null, lastReport: null } : cached;});useEffect(() => {- setHistory((previous) =>- recordRunningTokenRate(previous, {+ setHistory((previous) => {+ const recorded = recordRunningTokenRate(previous, {startedAt,outputTokens,generationDurationMs,generationReliable,- }),- );- }, [startedAt, outputTokens, generationDurationMs, generationReliable]);+ });+ return generationActive === false ? { ...recorded, latestRate: null, latestSampleAt: undefined } : recorded;+ });+ }, [startedAt, outputTokens, generationDurationMs, generationReliable, generationActive]);useEffect(() => {if (sessionKey) saveCachedRateHistory(sessionKey, history);}, [sessionKey, history]);diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex f656816b64..3b06929cac 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -10046,7 +10046,7 @@"waitSeconds": "{{seconds}}초","firstResponse": "첫 응답","streamWait": "스트림 내 대기",- "turnWaitDescription": "로컬 실행 시작부터 첫 텍스트, 사고 또는 도구 내용까지의 시간입니다. 네트워크 지연과는 다릅니다.",+ "turnWaitDescription": "로컬 공급자 턴 시작부터 첫 텍스트, 사고 또는 도구 내용까지의 시간입니다. 네트워크 지연과는 다릅니다.","streamWaitDescription": "SDK 스트림 시작부터 첫 콘텐츠까지의 시간입니다. 그 이전의 요청 대기는 측정할 수 없습니다.","lastGeneration": "지난 생성","finalAverage": "최종 평균",diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex 9cd9efc5f9..35a9d9870f 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -12077,6 +12077,7 @@ function ComposerActivityStatus({const samplerStartedAt = rateStartedAt === undefined ? startedAt : rateStartedAt;const legacyRateHistory = useRunningTokenRateHistory({sessionKey,+ generationActive,startedAt: samplerStartedAt,outputTokens,generationDurationMs,@@ -12084,7 +12085,8 @@ function ComposerActivityStatus({streaming,});- const rateHistory = responseSpeed ? responseSpeedHistory(responseSpeed) : legacyRateHistory;+ const rateHistory = responseSpeed ? responseSpeedHistory(responseSpeed)+ : generationActive === false ? { ...legacyRateHistory, latestRate: null } : legacyRateHistory;const completedSpeed = !visible && responseSpeed?.phase === 'complete';const speedActivity = responseSpeed ? responseSpeedActivity(responseSpeed) : null;if (!visible && !completedSpeed) return null;diff --git a/apps/mobile/src/__tests__/runningTokenRatePopover.test.tsx b/apps/mobile/src/__tests__/runningTokenRatePopover.test.tsxindex e9bc469b41..b1b80be20b 100644--- a/apps/mobile/src/__tests__/runningTokenRatePopover.test.tsx+++ b/apps/mobile/src/__tests__/runningTokenRatePopover.test.tsx@@ -272,6 +272,10 @@ it.each(["onPress", "onLongPress"])(expect(loadCachedRateHistory(base.sessionKey)?.samples.map((s) => s.rate),).toEqual([100]);+ await renderStatus({ startedAt: null, outputTokens: 100, generationDurationMs: 1000, generationActive: false });+ expect(card()!.textContent).toContain('session.screen.currentRate—');+ await renderStatus({ startedAt: null, outputTokens: 100, generationDurationMs: 1000, generationActive: true });+ expect(card()!.textContent).toContain('session.screen.currentRate—');for (const inactive of [{ sideTaskRunning: true },{ reconnectAttempt: { attempt: 1, maxAttempts: 3 } },diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.jsonindex 36e9968924..81478f42ac 100644--- a/apps/mobile/src/i18n/locales/ko/session.json+++ b/apps/mobile/src/i18n/locales/ko/session.json@@ -269,7 +269,7 @@"waitSeconds": "{{seconds}}초","firstResponse": "첫 응답","streamWait": "스트림 내 대기",- "turnWaitDescription": "로컬 실행 시작부터 첫 텍스트, 사고 또는 도구 내용까지의 시간입니다. 네트워크 지연과는 다릅니다.",+ "turnWaitDescription": "로컬 공급자 턴 시작부터 첫 텍스트, 사고 또는 도구 내용까지의 시간입니다. 네트워크 지연과는 다릅니다.","streamWaitDescription": "SDK 스트림 시작부터 첫 콘텐츠까지의 시간입니다. 그 이전의 요청 대기는 측정할 수 없습니다.","lastGeneration": "지난 생성","finalAverage": "최종 평균",diff --git a/apps/mobile/src/session/useRunningTokenRateHistory.ts b/apps/mobile/src/session/useRunningTokenRateHistory.tsindex 2fbcca018b..447cb9a434 100644--- a/apps/mobile/src/session/useRunningTokenRateHistory.ts+++ b/apps/mobile/src/session/useRunningTokenRateHistory.ts@@ -15,6 +15,7 @@ export function useRunningTokenRateHistory(input: {outputTokens: number;generationDurationMs: number;generationReliable: boolean;+ generationActive?: boolean;/** 本地发送或队列已让活动条出现,但远端本轮 startedAt 可能仍是 null。 */streaming?: boolean;}) {@@ -24,6 +25,7 @@ export function useRunningTokenRateHistory(input: {outputTokens,generationDurationMs,generationReliable,+ generationActive,streaming = false,} = input;// 挂载时从按会话的进程内缓存播种:ComposerActivityStatus 以账号、设备和任务身份为 key,@@ -66,9 +68,9 @@ export function useRunningTokenRateHistory(input: {) {return { ...recorded, baseline: null, lastReport: null, latestRate: null };}- return recorded;+ return generationActive === false ? { ...recorded, latestRate: null, latestSampleAt: undefined } : recorded;});- }, [sessionKey, startedAt, outputTokens, generationDurationMs, generationReliable, streaming]);+ }, [sessionKey, startedAt, outputTokens, generationDurationMs, generationReliable, generationActive, streaming]);useEffect(() => {if (sessionKey) saveCachedRateHistory(sessionKey, history);}, [sessionKey, history]);diff --git a/docs/dev-rules/response-speed.md b/docs/dev-rules/response-speed.mdindex db507acb0b..736ed7b1af 100644--- a/docs/dev-rules/response-speed.md+++ b/docs/dev-rules/response-speed.md@@ -16,7 +16,8 @@Claude 显示「流内等待」,SDK 暴露事件前的请求时间不可测。Pi/Codex 显示「首响应」。排队发生在引擎开始前,不进入等待或生成速度。-生成计时从内容开始,到响应结束或工具/审批暂停;工具结束后要等到下一次内容才恢复。+生成计时从内容开始,到响应结束或工具/审批暂停;最后一个工具/审批结束后重新显示等待,下一次内容才恢复;并行内容已恢复时不被工具结束打断。+Codex 在 `agentMessage` 完成时关闭观测响应,迟到 usage/turn 完成只校准计数,不延长生成时间。Pi 重试关闭失败片段,下一请求重新等待;每轮重新清空测量。零 usage 是有效零;缺少 usage则保留估算。仅结束事件有 output、没有可观测流,或检测到挂起/时钟异常时不提供 TPS。diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex a0d5509a16..cb359ed738 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -18378,6 +18378,8 @@ describe('CodexAgent MCP thread context hooks', () => {}now = 5_000;+ handlers.itemStarted!({ threadId: 'start-thread-id', turnId: 'turn-ordering',+ item: { id: 'ordering-reasoning', type: 'reasoning', summary: [], content: [] } });handlers.turnCompleted({threadId: 'start-thread-id',turn: { id: 'turn-ordering', status: 'completed' },@@ -18387,7 +18389,8 @@ describe('CodexAgent MCP thread context hooks', () => {});const done = events.find((event) => event.type === 'done');expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs)- .toBe(expectedDurationMs);+ .toBeUndefined();+ expect(events.findLast((event) => event.type === 'status')?.data.responseSpeed).toMatchObject({ outputTokens: 0, averageRate: null, firstResponseMs: expectedDurationMs });await handle.close();} finally {@@ -18396,6 +18399,74 @@ describe('CodexAgent MCP thread context hooks', () => {},);+ it.each(['serial', 'parallel-tools', 'parallel-output'])('publishes paired tool phases and closes response time before delayed usage/turn completion (%s)', async (mode) => {+ let now = 1_000;+ const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now);+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent);+ const handle = await agent.startSession({ sessionId: 'session-speed-lifecycle', model: 'gpt-5.4', workingDir: '/repo' });+ const handlers = host.getThreadHandlers()!;+ const events: AgentEvent[] = [];+ void (async () => { for await (const event of handle.events()) events.push(event); })();+ const latestSpeed = () => events.findLast((event) => event.type === 'status')?.data.responseSpeed;+ try {+ handlers.turnStarted!({ threadId: 'start-thread-id', turn: { id: 'speed-turn' } });+ now = 2_000;+ handlers.agentMessageDelta!({ threadId: 'start-thread-id', turnId: 'speed-turn', itemId: 'answer-1', delta: 'abcd' });+ now = 3_000;+ handlers.itemStarted!({ threadId: 'start-thread-id', turnId: 'speed-turn',+ item: { id: 'tool-1', type: 'commandExecution', command: 'pwd', cwd: '/repo', status: 'inProgress' } } as never);+ await waitForExpectation(() => expect(latestSpeed()).toMatchObject({ phase: 'paused', toolActive: true, durationMs: 1_000 }));+ // A duplicate start must not reopen generation during tool execution.+ now = 3_100;+ handlers.itemStarted!({ threadId: 'start-thread-id', turnId: 'speed-turn',+ item: { id: 'tool-1', type: 'commandExecution', command: 'pwd', cwd: '/repo', status: 'inProgress' } } as never);+ await waitForExpectation(() => expect(latestSpeed()).toMatchObject({ phase: 'paused', durationMs: 1_000 }));+ if (mode === 'parallel-tools') {+ now = 4_000;+ handlers.itemStarted!({ threadId: 'start-thread-id', turnId: 'speed-turn',+ item: { id: 'tool-2', type: 'commandExecution', command: 'pwd', cwd: '/repo', status: 'inProgress' } } as never);+ now = 8_000;+ handlers.itemCompleted!({ threadId: 'start-thread-id', turnId: 'speed-turn',+ item: { id: 'tool-2', type: 'commandExecution', command: 'pwd', cwd: '/repo', status: 'completed' } } as never);+ await waitForExpectation(() => expect(latestSpeed()).toMatchObject({ phase: 'paused', toolActive: true }));+ }+ if (mode === 'parallel-output') {+ now = 8_000;+ handlers.agentMessageDelta!({ threadId: 'start-thread-id', turnId: 'speed-turn', itemId: 'parallel-answer', delta: 'ijkl' });+ }+ now = 9_000;+ handlers.itemCompleted!({ threadId: 'start-thread-id', turnId: 'speed-turn',+ item: { id: 'tool-1', type: 'commandExecution', command: 'pwd', cwd: '/repo', status: 'completed', aggregatedOutput: '/repo' } } as never);+ await waitForExpectation(() => expect(latestSpeed()).toMatchObject({ phase: mode === 'parallel-output' ? 'generating' : 'waiting', toolActive: false, waitingMs: 0 }));+ now = 11_000;+ handlers.agentMessageDelta!({ threadId: 'start-thread-id', turnId: 'speed-turn', itemId: 'answer-2', delta: 'efgh' });+ now = 13_000;+ handlers.itemCompleted!({ threadId: 'start-thread-id', turnId: 'speed-turn',+ item: { id: 'answer-2', type: 'agentMessage', text: 'efgh' } } as never);+ const observedMs = mode === 'parallel-output' ? 6_000 : 3_000;+ await waitForExpectation(() => expect(latestSpeed()).toMatchObject({ phase: 'paused', durationMs: observedMs }));+ now = 19_000;+ handlers.tokenUsageUpdated!({ threadId: 'start-thread-id', turnId: 'speed-turn', tokenUsage: {+ total: { inputTokens: 10, cachedInputTokens: 0, outputTokens: 60, reasoningOutputTokens: 0, totalTokens: 70 },+ last: { inputTokens: 10, cachedInputTokens: 0, outputTokens: 60, reasoningOutputTokens: 0, totalTokens: 70 },+ } } as never);+ now = 25_000;+ handlers.turnCompleted!({ threadId: 'start-thread-id', turn: { id: 'speed-turn', status: 'completed', durationMs: 24_000 } });+ await waitForExpectation(() => expect(events.some((event) => event.type === 'done')).toBe(true));+ expect(latestSpeed()).toMatchObject({ phase: 'complete', outputTokens: 60, durationMs: observedMs, averageRate: 60_000 / observedMs, estimated: false });+ expect(events.find((event) => event.type === 'done')?.data.usage).toMatchObject({ completionTokens: 60, durationMs: observedMs });+ now = 26_000;+ handlers.turnStarted!({ threadId: 'start-thread-id', turn: { id: 'next-speed-turn' } });+ now = 26_100;+ handlers.itemStarted!({ threadId: 'start-thread-id', turnId: 'next-speed-turn', item: { id: 'reason-2', type: 'reasoning', summary: [], content: [] } } as never);+ await waitForExpectation(() => expect(latestSpeed()?.outputTokens).toBe(0));+ } finally {+ await handle.close();+ nowSpy.mockRestore();+ }+ });+it('starts response-first generation timing at turn/started and excludes an approval wait', async () => {let now = 1_000;const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now);@@ -18469,7 +18540,10 @@ describe('CodexAgent MCP thread context hooks', () => {});await waitForExpectation(() => expect(events.some((event) => event.type === 'done')).toBe(true));const done = events.find((event) => event.type === 'done');- expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs).toBe(3_000);+ // No root output/usage was observed: tool/interaction facts remain+ // available, but cannot become a persisted token-rate denominator.+ expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs).toBeUndefined();+ expect(events.findLast((event) => event.type === 'status')?.data.responseSpeed).toMatchObject({ outputTokens: 0, averageRate: null, firstResponseMs: null });await handle.close();} finally {@@ -18558,7 +18632,9 @@ describe('CodexAgent MCP thread context hooks', () => {expect(events.some((event) => event.type === 'done')).toBe(true),);const done = events.find((event) => event.type === 'done');- expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs).toBe(1_500);+ // A last-only usage notification without a cumulative ledger cursor and+ // no content stream cannot provide a calibrated generation rate.+ expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs).toBeUndefined();await handle.close();} finally {@@ -18634,7 +18710,10 @@ describe('CodexAgent MCP thread context hooks', () => {expect(handle.getUsageSnapshot().tokenUsage).toBe(540 - cachedInputTokens);handlers.turnCompleted!({ threadId: 'start-thread-id', turn: { id: 'turn-1', status: 'completed' } });await waitForExpectation(() => expect(events.some((event) => event.type === 'done')).toBe(true));- expect(events.find((event) => event.type === 'done')?.data.usage.durationMs).toBe(5_000);+ // Real output exists, but no streamed text was observed: keep accounting+ // and the legacy paired sample, while omitting an unobservable final TPS.+ expect(events.find((event) => event.type === 'done')?.data.usage.durationMs).toBeUndefined();+ expect(events.filter((event) => event.type === 'status').at(-1)?.data.responseSpeed).toMatchObject({ outputTokens: 500, averageRate: null });expect(events.filter((event) => event.type === 'status').at(-1)?.data).toMatchObject({status: 'Done', outputTokens: 500, generationDurationMs: 5_000,});@@ -19003,7 +19082,10 @@ describe('CodexAgent MCP thread context hooks', () => {});await waitForExpectation(() => expect(events.some((event) => event.type === 'done')).toBe(true));const done = events.find((event) => event.type === 'done');- expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs).toBe(3_000);+ // No root output/usage was observed: tool/interaction facts remain+ // available, but cannot become a persisted token-rate denominator.+ expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs).toBeUndefined();+ expect(events.findLast((event) => event.type === 'status')?.data.responseSpeed).toMatchObject({ outputTokens: 0, averageRate: null, firstResponseMs: 1_000 });await handle.close();} finally {@@ -19081,7 +19163,10 @@ describe('CodexAgent MCP thread context hooks', () => {});await waitForExpectation(() => expect(events.some((event) => event.type === 'done')).toBe(true));const done = events.find((event) => event.type === 'done');- expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs).toBe(3_000);+ // No root output/usage was observed: tool/interaction facts remain+ // available, but cannot become a persisted token-rate denominator.+ expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs).toBeUndefined();+ expect(events.findLast((event) => event.type === 'status')?.data.responseSpeed).toMatchObject({ outputTokens: 0, averageRate: null, firstResponseMs: null });if (outcome === 'server-resolved') {decision.resolve({ kind: 'ask_user_question', answers: {} });diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 0970e5c839..37741bf0d4 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -168,6 +168,7 @@ import {classifyCodexError,translateErrorNotification,translateItemNotification,+ observeCodexItemTiming,beginCodexGenerationTurn,finalizeCodexGenerationTurn,pauseCodexGeneration,@@ -12311,10 +12312,12 @@ assertRouteCurrent();params.turnId,'started',);+ observeCodexItemTiming(translatorRt, 'started', translatedParams);pushItemStatus(translatedItem);translateItemNotification('started', translatedParams, eventQueue, {rt: translatorRt,log,+ timingObserved: true,onCompactBoundary: handleCompactBoundary,});// 重放帧后发:translator 刚推的 running 帧不得把已重放出的终态盖回去。@@ -12449,6 +12452,12 @@ assertRouteCurrent();log,onCompactBoundary: handleCompactBoundary,});+ // Close the observed response after translating any final text that+ // was absent from deltas. A later usage/turn terminal calibrates the+ // counts without charging its delivery lag as model generation.+ if (!isLateCollabTerminal && translatedItem.type === 'agentMessage') {+ translatorRt.responseSpeed.pause();+ }// A late V1 spawn completion is the spawn tool closing, not necessarily// the child closing. Reassert a running compact state, or an explicit// failed/stopped tracker state; a completed replay would only duplicatediff --git a/packages/maker-core/src/agents/codex/translator.ts b/packages/maker-core/src/agents/codex/translator.tsindex 0808959a29..a24f5a203e 100644--- a/packages/maker-core/src/agents/codex/translator.ts+++ b/packages/maker-core/src/agents/codex/translator.ts@@ -278,6 +278,12 @@ export function resumeCodexGeneration(return;}if (rt.generationPendingToolIds.size === 0) rt.generationStartedAt = resumedAt;+ // Completion of the last tool/approval is a locally observed waiting+ // boundary, not evidence that the next model response has started. Preserve+ // a parallel response that already resumed on an actual output delta.+ if (rt.generationPendingToolIds.size === 0 && rt.responseSpeed.snapshot(resumedAt).phase === 'paused') {+ rt.responseSpeed.beginRequest(resumedAt);+ }if (rt.generationPendingToolIds.size === 0) startCodexGenerationHeartbeat(rt);}@@ -350,6 +356,8 @@ interface TranslatorLog {export interface CodexTranslateContext {rt: CodexRuntimeState;log: TranslatorLog;+ /** Host observed the boundary before publishing its status frame. */+ timingObserved?: boolean;/*** Maker Memory flush 观察器 — codex contextCompaction completed 时调,* controller 重置 fired 阈值 (compact 后 context 又有空间, 可重新触发)。@@ -381,6 +389,23 @@ export interface CodexTranslateContext {type ItemPhase = 'started' | 'updated' | 'completed';+/** Observe before status publication without changing the established event order. */+export function observeCodexItemTiming(+ rt: CodexRuntimeState,+ phase: ItemPhase,+ notification: ItemStartedNotification['params'] | ItemUpdatedNotification['params'] | ItemCompletedNotification['params'],+): void {+ const item = notification.item;+ const itemType = item?.type;+ if (!item || typeof item !== 'object') return;+ if (phase === 'started' && CODEX_GENERATION_PAUSE_ITEM_TYPES.has(itemType)+ && rt.generationPendingToolIds.has(`item:${item.id}`)) return;+ if (phase === 'started' && (itemType === 'reasoning' || CODEX_GENERATION_PAUSE_ITEM_TYPES.has(itemType))) {+ rt.responseSpeed.content();+ }+ noteCodexGenerationBoundary(rt, phase, item, notification);+}+export function translateItemNotification(phase: ItemPhase,notification:@@ -400,15 +425,7 @@ export function translateItemNotification(ctx.log.warn('item missing type field', { phase, itemKeys: Object.keys(item) });return;}- if (phase === 'started' && (itemType === 'reasoning' || CODEX_GENERATION_PAUSE_ITEM_TYPES.has(itemType))) {- ctx.rt.responseSpeed.content();- }- noteCodexGenerationBoundary(- ctx.rt,- phase,- item as { id?: unknown; type?: unknown },- notification as { turnId?: unknown },- );+ if (!ctx.timingObserved) observeCodexItemTiming(ctx.rt, phase, notification);switch (itemType) {case 'agentMessage':diff --git a/packages/maker-core/src/agents/shared/response-speed.test.ts b/packages/maker-core/src/agents/shared/response-speed.test.tsindex 74b0e890e7..0dc43634ec 100644--- a/packages/maker-core/src/agents/shared/response-speed.test.ts+++ b/packages/maker-core/src/agents/shared/response-speed.test.ts@@ -149,6 +149,7 @@ describe('response speed', () => {return speed.snapshot(2_000).outputTokens;};expect(measure(['hello 世界 👋'])).toBe(measure(['h', 'ello ', '世', '界 ', '👋']));+ expect(measure(['👋'.repeat(10)])).toBe(measure('👋'.repeat(10).split('')));const speed = new ResponseSpeedTracker();speed.reset('turn', 0);for (let i = 1; i < 500; i++) speed.delta('a', i * 250);diff --git a/packages/maker-core/src/agents/shared/response-speed.ts b/packages/maker-core/src/agents/shared/response-speed.tsindex 116bcdadf2..118a4fc3d2 100644--- a/packages/maker-core/src/agents/shared/response-speed.ts+++ b/packages/maker-core/src/agents/shared/response-speed.ts@@ -73,7 +73,7 @@ export class ResponseSpeedTracker {this.content(now);// Additive across arbitrary chunks; no regex word-boundary or per-delta rounding.let units = 0;- for (const character of text) units += character.codePointAt(0)! > 0xff ? 0.67 : 0.25;+ for (const character of text) units += character.charCodeAt(0) > 0xff ? 0.67 * character.length : 0.25;this.units += units;this.reported = null;this.lastDeltaAt = now;