Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(chat): fold failed sampling output before a successful retry
shenjiachengdb6b33075442
diff --git a/apps/desktop/src/renderer/__tests__/workGroupProjectionParity.test.ts b/apps/desktop/src/renderer/__tests__/workGroupProjectionParity.test.tsindex 86c26d5d24..2780e6cd5a 100644--- a/apps/desktop/src/renderer/__tests__/workGroupProjectionParity.test.ts+++ b/apps/desktop/src/renderer/__tests__/workGroupProjectionParity.test.ts@@ -18,6 +18,7 @@ interface Event {sealed?: boolean;autoResume?: boolean;delivery?: 'steer' | 'turn';+ failedSamplingAttempt?: boolean;}const iso = (seconds: number) => new Date(Date.UTC(2026, 0, 1) + seconds * 1000).toISOString();@@ -76,6 +77,7 @@ function desktopItems(events: readonly Event[]): RenderItem[] {: {}),createdAt: iso(event.at),turnCompleted: event.sealed,+ failedSamplingAttempt: event.failedSamplingAttempt,delivery: event.delivery,...(event.autoResume ? { systemCardType: 'auto-resume' as const } : {}),...(event.kind === 'compact' ? { systemCardType: 'compact' as const } : {}),@@ -95,6 +97,7 @@ function normalized(events: readonly Event[]): MessageRenderNormalizedMessage[]body: event.body ?? (event.kind === 'thinking' ? 'Thinking' : ''),createdAt: iso(event.at),turnCompleted: event.sealed,+ failedSamplingAttempt: event.failedSamplingAttempt,settledAt: event.end === undefined ? undefined : iso(event.end),source: {clientId: event.id,@@ -161,6 +164,48 @@ function tree(items: readonly Projection[]): unknown[] {}const cases: Array<{ name: string; events: Event[]; streaming?: boolean; expected: unknown[] }> = [+ // #6351: both platform consumers must fold failed native attempts without+ // waiting for a successful final. Normal multi-message answers stay intact.+ {+ name: 'failed sampling attempts fold while the native retry is still running',+ streaming: true,+ events: [user(),+ { ...answer('failed1', 1, true, '# Opening'), failedSamplingAttempt: true },+ { ...answer('failed2', 2), failedSamplingAttempt: true }],+ expected: [['u'], ['work-failed1', [['failed1'], ['failed2']]]],+ },+ {+ name: 'exhausted or stopped sampling attempts fold without a successful final',+ events: [user(),+ { ...answer('failed1', 1, true, '# Opening'), failedSamplingAttempt: true },+ { ...answer('failed2', 2), failedSamplingAttempt: true },+ { id: 'failure', kind: 'error', at: 3, body: 'Reply interrupted' }],+ expected: [['u'], ['work-failed1', [['failed1'], ['failed2']]], ['failure']],+ },+ {+ name: 'a successful retry preserves all normal contiguous assistant answer blocks',+ events: [user(),+ { ...answer('failed1', 1), failedSamplingAttempt: true },+ { ...answer('failed2', 2), failedSamplingAttempt: true },+ answer('intro', 3), answer('final', 4, true)],+ expected: [['u'], ['work-failed1', [['failed1'], ['failed2']]], ['intro'], ['final']],+ },+ {+ name: 'manual recovery leaves the prior failed fold and error in their own user turn',+ events: [user(),+ { ...answer('failed1', 1), failedSamplingAttempt: true },+ { id: 'failure', kind: 'error', at: 2, body: 'Reply interrupted' },+ user('recovery', 3), answer('final', 4, true)],+ expected: [['u'], ['work-failed1', [['failed1']]], ['failure'], ['recovery'], ['final']],+ },+ {+ name: 'steering stays ordered between failed samples and the successful reply',+ events: [user(),+ { ...answer('failed1', 1), failedSamplingAttempt: true },+ { ...user('steer', 2), delivery: 'steer' },+ { ...answer('failed2', 3), failedSamplingAttempt: true }, answer('final', 4, true)],+ expected: [['u'], ['work-failed1', [['failed1']]], ['steer'], ['work-failed2', [['failed2']]], ['final']],+ },{name: 'running subagent remains visible between completed work groups',events: [diff --git a/apps/desktop/src/renderer/components/chat/messageWorkGroups.ts b/apps/desktop/src/renderer/components/chat/messageWorkGroups.tsindex 4ec5557229..57807ca2cb 100644--- a/apps/desktop/src/renderer/components/chat/messageWorkGroups.ts+++ b/apps/desktop/src/renderer/components/chat/messageWorkGroups.ts@@ -171,8 +171,8 @@ export function isCompletedAssistantMessage(message: ChatMessage): boolean {}/** 完成态 work_group 可合并的子项:tool_segment / agent_task / thinking /- * assistant 工作文字。运行态只通过 isWorkActivityItem 收动作,所以不会提前- * 折叠正在输出的 assistant 文字。 */+ * assistant 工作文字。正常流式正文不会提前折叠;已证实失败的采样输出+ * 复用活动折叠,无需等待成功答复出现。 */function isWorkChild(it: RenderItem): it is WorkChildItem {return (it.type === 'tool_segment' ||@@ -212,8 +212,8 @@ function isWorkflowTaskItem(it: RenderItem): boolean {);}-/** preview 中计为一条真实活动的 render item。assistant 进度文字- * 始终留在主消息流,不占最近 5 条活动窗口。 */+/** Normal assistant progress stays in the main stream. SDK-proven failed+ * sampling output uses the existing work fold even before a retry succeeds. */function isWorkActivityItem(it: RenderItem): it is WorkChildItem {return (!isRunningAgentTask(it) &&@@ -221,7 +221,8 @@ function isWorkActivityItem(it: RenderItem): it is WorkChildItem {!isWorkflowTaskItem(it) &&(it.type === 'tool_segment' ||it.type === 'agent_task' ||- (it.type === 'message' && it.message.role === 'thinking'))+ (it.type === 'message' && (it.message.role === 'thinking' ||+ (it.message.role === 'assistant' && it.message.failedSamplingAttempt === true)))));}@@ -491,7 +492,7 @@ function createCompletedWorkGroup(prevBoundaryTs: number | null = null,): WorkGroupRenderItem {const hasAssistantText = run.some(- (item) => item.type === 'message' && item.message.role === 'assistant',+ (item) => item.type === 'message' && item.message.role === 'assistant' && !item.message.failedSamplingAttempt,);if (!hasAssistantText) return createWorkGroup(run, nextItem, false, prevBoundaryTs);diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.tsindex 9f5e43dc9b..66177c97b1 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.ts+++ b/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.ts@@ -25,17 +25,25 @@ describe('teammate final-result presentation', () => {// #6351: provider final_answer only closes a message, not a successful sample.// Failed output remains in the expandable work history rather than being lifted// beside the real answer; normal commentary is governed by the existing rules.- it('retains failed sampling output in work history without lifting it as another successful reply', () => {- const result = project([- message('u', 'user'),- message('failed', 'assistant', 'Opening from failed attempt', {- assistantPhase: 'final_answer', failedSamplingAttempt: true, turnCostUsd: 0.1,- }),- message('success', 'assistant', 'Successful opening', { assistantPhase: 'final_answer', turnCompleted: true }),- ], false);- expect(proseIds(result)).toEqual(['success']);- expect(allKeys(result)).toContain('msg-failed');- });+ it.each(['retrying', 'completed', 'exhausted', 'stopped'] as const)(+ 'retains failed sampling output in work history when the retry is %s', (ending) => {+ const result = project([+ message('u', 'user'),+ message('failed', 'assistant', 'Opening from failed attempt', {+ assistantPhase: 'final_answer', failedSamplingAttempt: true, turnCostUsd: 0.1,+ }),+ message('failed-commentary', 'assistant', 'Preparing another opening', {+ assistantPhase: 'commentary', failedSamplingAttempt: true,+ }),+ ...(ending === 'completed'+ ? [message('intro', 'assistant', 'Accepted intro'),+ message('success', 'assistant', 'Successful opening', { assistantPhase: 'final_answer', turnCompleted: true })]+ : ending === 'retrying' ? [] : [message('error', 'error', 'Reply interrupted')]),+ ], ending === 'retrying');+ expect(proseIds(result)).toEqual(ending === 'completed' ? ['intro', 'success'] : []);+ expect(allKeys(result)).toContain('msg-failed');+ expect(allKeys(result)).toContain('msg-failed-commentary');+ });it('keeps coordination input hidden while process, explicit inputs, results and errors remain visible', () => {const rows = [message('coordination', 'user', '[UI_ACTION_TRIGGER]File agreement', { isSyntheticTrigger: true }),tool('audit'), message('visible-input', 'user', 'Requested status'),diff --git a/apps/mobile/src/__tests__/companionConversationPresentation.test.ts b/apps/mobile/src/__tests__/companionConversationPresentation.test.tsindex b7e367501d..393f2dd49b 100644--- a/apps/mobile/src/__tests__/companionConversationPresentation.test.ts+++ b/apps/mobile/src/__tests__/companionConversationPresentation.test.ts@@ -11,6 +11,30 @@ const bodies = (messages: RemoteMessage[], running: boolean) => companionConversconst base = [row('u0', 'user', 'Help'), row('a1', 'assistant', 'Public progress'),row('t2', 'tool_use', { toolName: 'Read', toolUseId: 't', input: { path: 'private' } }),row('r3', 'tool_result', { toolUseId: 't', result: 'technical details' })];+// #6351: this consumer expands work groups and infers contiguous sealed runs,+// so grouping alone cannot prevent a failed sample becoming another reply.+it.each(['retrying', 'completed', 'exhausted'] as const)(+ 'does not promote failed sampling prose in a %s companion turn', (ending) => {+ const failed = row('a1', 'assistant', '# Failed opening\n' + 'Details '.repeat(100), {+ turnCompleted: true, turnCostUsd: 0.1, failedSamplingAttempt: {+ threadId: 'thread', turnId: 'turn', attempt: 1, itemId: 'failed',+ },+ });+ const source = [row('u0', 'user', 'Help'), failed,+ ...(ending === 'completed' ? [row('a2', 'assistant', 'Accepted intro'),+ row('a3', 'assistant', 'Accepted answer', { turnCompleted: true })]+ : ending === 'exhausted' ? [row('e2', 'error', 'Model failed')] : []),+ ];+ const visible = bodies(source, ending === 'retrying')+ .filter(item => item.type === 'message').map(item => item.message);+ expect(visible.filter(item => item.kind === 'assistant').map(item => item.body))+ .toEqual(ending === 'completed' ? ['Accepted intro', 'Accepted answer'] : []);+ expect(visible.some(item => item.source.id === 'u0')).toBe(true);+ expect(visible.some(item => item.source.role === 'error')).toBe(ending === 'exhausted');+ expect(source[1]).toBe(failed);+ expect(source[1].content).toContain('# Failed opening');+ expect(source[1].agentMeta?.failedSamplingAttempt).toBeDefined();+ });it('has no process entry or commentary during generation, and retains the completed answer', () => {const active = bodies(base, true);expect(active.map(item => item.type)).toEqual(['message']);diff --git a/apps/mobile/src/__tests__/messageRenderModel.test.ts b/apps/mobile/src/__tests__/messageRenderModel.test.tsindex 98c2107ceb..463ec6387b 100644--- a/apps/mobile/src/__tests__/messageRenderModel.test.ts+++ b/apps/mobile/src/__tests__/messageRenderModel.test.ts@@ -39,6 +39,36 @@ function toolUse(id: string, toolName: string, input: unknown, seconds: number):}describe('messageRenderModel', () => {+ // #6351: remote JSON must reach the actual work fold, not only normalization.+ // Two completed items from failed samples must not look like accepted replies.+ it('folds remote failed samples before success and retains their original records', () => {+ const messages = [+ message({ id: 'u', role: 'user', content: 'Start', createdAt: at(1) }),+ ...[1, 2].map((attempt) => message({+ id: `failed${attempt}`, role: 'assistant', content: '# Opening', createdAt: at(attempt + 1),+ agentMeta: { turnCompleted: true, turnCostUsd: 0.1, failedSamplingAttempt: {+ threadId: 'thread', turnId: 'turn', attempt, itemId: `item${attempt}`,+ } },+ })),+ ];+ for (const isSessionStreaming of [true, false]) {+ const items = buildMobileMessageRenderItems(messages, { isSessionStreaming });+ expect(items.map((item) => item.key)).toEqual(['message-u', 'work-failed1']);+ expect(items[1]).toMatchObject({ type: 'work_group', children: [+ { type: 'message', message: { source: messages[1], failedSamplingAttempt: true } },+ { type: 'message', message: { source: messages[2], failedSamplingAttempt: true } },+ ] });+ }+ const completed = buildMobileMessageRenderItems([...messages,+ message({ id: 'intro', role: 'assistant', content: 'Accepted intro', createdAt: at(4) }),+ message({ id: 'final', role: 'assistant', content: 'Accepted answer', createdAt: at(5),+ agentMeta: { turnCompleted: true } }),+ ], { isSessionStreaming: false });+ expect(completed.map((item) => item.key)).toEqual([+ 'message-u', 'work-failed1', 'message-intro', 'message-final',+ ]);+ });+it('keeps completed work folded when the next remote run starts before its user row arrives', () => {const messages = [message({ id: 'u1', role: 'user', content: 'start', createdAt: at(1) }),diff --git a/apps/mobile/src/session/companionConversationPresentation.ts b/apps/mobile/src/session/companionConversationPresentation.tsindex 8de2f09dcc..48ae8611ad 100644--- a/apps/mobile/src/session/companionConversationPresentation.ts+++ b/apps/mobile/src/session/companionConversationPresentation.ts@@ -4,7 +4,7 @@ import { collectMobileMarkdownImages } from './messageMarkdown';import type { MobileMessageRenderItem } from './messageRenderModel';const isDelivery = (item: MobileMessageRenderItem) => item.type === 'tool_media' && item.tools.some(tool => !!tool.media?.length || !!tool.files?.length)- || item.type === 'message' && (item.message.companion?.kind === 'task' && item.message.companion.meta.role === 'delegation-result'+ || item.type === 'message' && !item.message.failedSamplingAttempt && (item.message.companion?.kind === 'task' && item.message.companion.meta.role === 'delegation-result'|| !!item.message.attachments?.length || !!item.message.media?.length|| !!item.message.files?.length || collectMobileMarkdownImages(item.message.body).length > 0);@@ -19,7 +19,7 @@ export function companionConversationItems(items: readonly MobileMessageRenderItlet sealedRun = false;let nextAssistantAt: number | null = null;for (const item of expandWorkGroups(items).reverse()) {- if (item.type !== 'message' || item.message.kind !== 'assistant' || !item.message.body.trim() || item.message.systemCardType) {+ if (item.type !== 'message' || item.message.kind !== 'assistant' || item.message.failedSamplingAttempt || !item.message.body.trim() || item.message.systemCardType) {sealedRun = false;nextAssistantAt = null;} else {@@ -53,7 +53,7 @@ export function companionConversationItems(items: readonly MobileMessageRenderItelse if (delivery) deliveredAfter.add(item.key);}const attached = new Set(flattened.flatMap(item => item.type === 'message'- && item.message.kind === 'assistant' && item.message.turnCompleted === true && item.message.body.trim()+ && item.message.kind === 'assistant' && !item.message.failedSamplingAttempt && item.message.turnCompleted === true && item.message.body.trim()? readBotTaskResults(item.message.source.agentMeta?.botTaskResults).map(botTaskResultKey) : []));return flattened.filter(item => {if (item.type === 'message' && item.message.companion?.kind === 'task'@@ -63,6 +63,9 @@ export function companionConversationItems(items: readonly MobileMessageRenderIt|| item.type === 'subagent_group' || item.type === 'todo') return false;if (item.type !== 'message') return true;const message = item.message;+ // Companion chats omit process prose; the original failed rows remain in+ // persisted history and the ordinary task's expandable work group.+ if (message.kind === 'assistant' && message.failedSamplingAttempt) return false;// Desktop drops persisted synthetic resume separators from teammate chats; only the live// reconnect card (still in progress) remains. The composer status carries recovery copy.if (message.isSyntheticTrigger && message.systemCardType === 'auto-resume') {diff --git a/packages/maker-core/src/agents/codex/sampling-retry.integration.test.ts b/packages/maker-core/src/agents/codex/sampling-retry.integration.test.tsindex e4450d5c93..16105c3959 100644--- a/packages/maker-core/src/agents/codex/sampling-retry.integration.test.ts+++ b/packages/maker-core/src/agents/codex/sampling-retry.integration.test.ts@@ -44,12 +44,19 @@ it.skipIf(!binaryPath).each(['success', 'exhausted', 'stop', 'steer'] as const)(for await (const chunk of req) chunks.push(Buffer.from(chunk));requests.push(JSON.parse(Buffer.concat(chunks).toString('utf8')));const request = requests.length;+ const willComplete = recover || request > 2 || (request === 2 && ending === 'success');res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'close' });sendEvent(res, { type: 'response.created', response: { id: 'response-' + request } });+ if (willComplete) {+ for (const [id, phase] of [['accepted-commentary-', 'commentary'], ['accepted-intro-', 'final_answer']] as const) {+ sendEvent(res, { type: 'response.output_item.done', item: { type: 'message', role: 'assistant',+ id: id + request, phase, content: [{ type: 'output_text', text: id + request }] } });+ }+ }sendEvent(res, { type: 'response.output_item.done', item: { type: 'message', role: 'assistant',id: 'answer-' + request, phase: 'final_answer',content: [{ type: 'output_text', text: 'Opening from request ' + request }] } });- if (recover || request > 2 || (request === 2 && ending === 'success')) {+ if (willComplete) {complete(res, request);} else if (request === 2 && (ending === 'stop' || ending === 'steer')) {heldResponse = res;@@ -138,6 +145,14 @@ it.skipIf(!binaryPath).each(['success', 'exhausted', 'stop', 'steer'] as const)((event.data as { text?: string }).text)).toContain('Opening from request 1');expect(events.some(event => event.type === 'error' &&(event.data as { willRetry?: boolean }).willRetry === true)).toBe(true);+ if (ending === 'success' || ending === 'steer') {+ const acceptedRequest = ending === 'success' ? 2 : 3;+ const acceptedIds = ['accepted-commentary-' + acceptedRequest, 'accepted-intro-' + acceptedRequest];+ const textIds = events.filter(event => event.type === 'text').map(event =>+ (event.data as { agentMessageId?: string }).agentMessageId);+ expect(textIds).toEqual(expect.arrayContaining(acceptedIds));+ expect(failures.flatMap(failure => failure.agentMessageIds).some(id => acceptedIds.includes(id))).toBe(false);+ }const failureCount = failures.length;recover = true;const boundary = events.length;diff --git a/packages/maker-core/src/agents/codex/translator.test.ts b/packages/maker-core/src/agents/codex/translator.test.tsindex e285d1e32d..2f5f0e4169 100644--- a/packages/maker-core/src/agents/codex/translator.test.ts+++ b/packages/maker-core/src/agents/codex/translator.test.ts@@ -122,9 +122,16 @@ describe('Codex assistant text streaming contract', () => {translateErrorNotification(makeParams({ willRetry: true,message: 'stream disconnected - retrying sampling request (1/5 in 212ms)...',codexErrorInfo: { responseStreamDisconnected: {} } }), q, ctx);- complete('successful-answer', 'Hello from attempt two', 'final_answer');+ complete('successful-commentary', 'Preparing the accepted answer', 'commentary');+ complete('successful-intro', 'Hello from attempt two', 'final_answer');+ complete('successful-answer', 'The accepted answer continues', 'final_answer');+ expect(finishCodexSamplingTurn(rt, 't1', 'turn-a', 'completed')).toBeUndefined();const events = await collect(q);- expect(events.filter(event => event.type === 'text')).toHaveLength(4);+ expect(events.filter(event => event.type === 'text').map(event =>+ (event.data as { agentMessageId?: string }).agentMessageId)).toEqual([+ 'progress', 'failed-commentary', 'failed-answer',+ 'successful-commentary', 'successful-intro', 'successful-answer',+ ]);expect(events.find(event => event.type === 'error')).toMatchObject({data: { isTerminal: false, willRetry: true, assistantAttemptFailure: {threadId: 't1', turnId: 'turn-a', attempt: 1,diff --git a/packages/maker-shared/src/messageRender.ts b/packages/maker-shared/src/messageRender.tsindex 7d63cee2fe..ae9eaee328 100644--- a/packages/maker-shared/src/messageRender.ts+++ b/packages/maker-shared/src/messageRender.ts@@ -105,6 +105,8 @@ export interface MessageRenderNormalizedMessage<agentTaskStatus?: AgentTaskTerminalStatus;/** Host 在 SDK done 边界写入。同一 user turn 的最后一次 seal 是最终答复;更早的 seal 只在带交付内容时留在工作过程外。 */turnCompleted?: boolean;+ /** SDK-proven failed sampling output remains readable inside the work fold. */+ failedSamplingAttempt?: boolean;/** tool 消息专用:配对 tool_result 提取出的产出媒体(驱动 tool_media 独立渲染项)。 */media?: readonly MessageRenderToolMediaLike[];files?: readonly { url: string; title: string }[];@@ -1573,7 +1575,7 @@ function isRunningAgentTaskItem<}function isCompletedAssistantMessage(message: MessageRenderNormalizedMessage): boolean {- return message.turnCompleted === true;+ return !message.failedSamplingAttempt && message.turnCompleted === true;}function isAssistantAnswerCandidate<@@ -1581,6 +1583,7 @@ function isAssistantAnswerCandidate<>(item: MessageRenderItem<TMessage>): item is MessageRenderMessageItem<TMessage> {return item.type === 'message'&& item.message.kind === 'assistant'+ && !item.message.failedSamplingAttempt&& item.message.body.trim().length > 0;}@@ -1654,6 +1657,7 @@ function isDeliveryProseItem<TMessage extends MessageRenderNormalizedMessage>(): boolean {return item.type === 'message'&& item.message.kind === 'assistant'+ && !item.message.failedSamplingAttempt&& isDeliveryProseText(item.message.body);}@@ -1672,12 +1676,13 @@ function isWorkChild<);}-/** Assistant progress text remains visible while running and never consumes the latest-five window. */+/** Normal progress stays visible; proven failed sampling output uses the existing fold. */function isWorkActivityItem<TMessage extends MessageRenderNormalizedMessage>(item: MessageRenderItem<TMessage>,-): item is MessageRenderThinkingItem<TMessage> | MessageRenderToolGroupItem<TMessage> | MessageRenderAgentTaskItem<TMessage> {+): item is Exclude<MessageRenderWorkChildItem<TMessage>, MessageRenderWorkGroupItem<TMessage>> {return !isRunningAgentTaskItem(item)- && (item.type === 'thinking' || item.type === 'tool_group' || item.type === 'agent_task');+ && (item.type === 'thinking' || item.type === 'tool_group' || item.type === 'agent_task' ||+ (item.type === 'message' && item.message.kind === 'assistant' && item.message.failedSamplingAttempt === true));}/** 边界项(用户消息 / assistant 正文)的时间戳;非 message 卡片不作为时间边界。 */@@ -1724,7 +1729,7 @@ function createCompletedWorkGroup<TMessage extends MessageRenderNormalizedMessagpreviousBoundaryMs: number | null = null,): MessageRenderWorkGroupItem<TMessage> {const hasAssistantText = run.some(- (item) => item.type === 'message' && item.message.kind === 'assistant',+ (item) => item.type === 'message' && item.message.kind === 'assistant' && !item.message.failedSamplingAttempt,);if (!hasAssistantText) return createWorkGroup(run, nextItem, false, previousBoundaryMs);