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(codex): mark failed sampling replies across stream retries

shenjiacheng87f10f184748
diff --git a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
index 71338ddf1d..097e3553db 100644
--- a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
+++ b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
@@ -16,6 +16,55 @@ import { readTaskResultsForReply } from '../botTaskReplyResults.js';
import { describe, it, expect, vi, beforeEach } from 'vitest';
+// #6351: a completed text item can still belong to a failed sampling request.
+// The observable contract is durable metadata plus the existing row broadcast;
+// original text, successful retries and other turns/sessions must stay intact.
+it('marks exact failed assistant items, including a live block, without rewriting prose', async () => {
+ const sessionId = 'sampling-failure';
+ const otherSession = 'sampling-other-session';
+ clearSessionPersistState(sessionId);
+ clearSessionPersistState(otherSession);
+ const first = onAssistantTextEvent(sessionId, { agentMessageId: 'failed-1',
+ text: 'First opening', isFinal: true, isFullText: true }, null);
+ const second = onAssistantTextEvent(sessionId, { agentMessageId: 'failed-2',
+ text: 'Partial opening', isFinal: false }, null);
+ onAssistantTextEvent(otherSession, { agentMessageId: 'failed-1',
+ text: 'Other session', isFinal: true }, null);
+ onAssistantAttemptFailure(sessionId, { assistantAttemptFailure: {
+ threadId: 'native-thread', turnId: 'native-turn', attempt: 1,
+ agentMessageIds: ['failed-1', 'failed-2', 'unknown-item'],
+ } });
+ // A textless completion after this failure must not seal the failed reply.
+ expect(consumeLastTopLevelAssistantPersistId(sessionId)).toBeUndefined();
+ onAssistantTextEvent(sessionId, { agentMessageId: 'success',
+ text: 'Successful opening', isFinal: true, isFullText: true }, null);
+ await drainPersistQueue();
+ expect(patchMessageAgentMetaWithResult).toHaveBeenCalledWith(sessionId, first, {
+ failedSamplingAttempt: { threadId: 'native-thread', turnId: 'native-turn', attempt: 1, itemId: 'failed-1' },
+ turnCompleted: false,
+ });
+ expect(createMessage).toHaveBeenCalledWith(sessionId, expect.objectContaining({
+ clientId: second, content: 'Partial opening', agentMeta: expect.objectContaining({
+ failedSamplingAttempt: { threadId: 'native-thread', turnId: 'native-turn', attempt: 1, itemId: 'failed-2' },
+ }),
+ }), expect.anything());
+ expect(createMessage).toHaveBeenCalledWith(sessionId, expect.objectContaining({
+ content: 'Successful opening', agentMeta: null,
+ }), expect.anything());
+ expect(updateMessageContent).not.toHaveBeenCalled();
+ expect(broadcastMessageAgentMetaUpdate).toHaveBeenCalledWith(sessionId, first, expect.anything());
+ expect(vi.mocked(patchMessageAgentMetaWithResult).mock.calls.every(([id]) => id === sessionId)).toBe(true);
+ resetTurnPersistState(sessionId);
+ vi.mocked(patchMessageAgentMetaWithResult).mockClear();
+ onAssistantAttemptFailure(sessionId, { assistantAttemptFailure: {
+ threadId: 'native-thread', turnId: 'native-turn', attempt: 1, agentMessageIds: ['failed-1'],
+ } });
+ await drainPersistQueue();
+ expect(patchMessageAgentMetaWithResult).not.toHaveBeenCalled();
+ clearSessionPersistState(sessionId);
+ clearSessionPersistState(otherSession);
+});
+
vi.mock('../localDb/ipc/messages.js', () => ({
broadcastMessageAgentMetaUpdate: vi.fn(async () => true),
broadcastMessageRow: vi.fn(),
@@ -84,6 +133,7 @@ import {
onToolResultFullEvent,
prepareSyntheticToolEventForBroadcast,
onAssistantTextEvent,
+ onAssistantAttemptFailure,
drainPersistQueue,
onStandaloneTextEvent,
getSessionTextSnapshot,
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
index 4873089fe9..c229c6d993 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
@@ -123,6 +123,7 @@ vi.mock('../../messagePersistBroadcaster.js', () => ({
enqueueDurableWrite: effects.fn('enqueueDurableWrite'),
flushAssistantBlock: effects.fn('flushAssistantBlock'),
onAssistantTextEvent: effects.fn('onAssistantTextEvent'),
+ onAssistantAttemptFailure: effects.fn('onAssistantAttemptFailure'),
onStandaloneTextEvent: effects.fn('onStandaloneTextEvent'),
onAgentTaskUpdateEvent: effects.fn('onAgentTaskUpdateEvent'),
onThinkingEvent: effects.fn('onThinkingEvent'),
diff --git a/apps/desktop/src/main/maker-ipc/sessionEventStream.ts b/apps/desktop/src/main/maker-ipc/sessionEventStream.ts
index 824536c4ac..e2a01c8754 100644
--- a/apps/desktop/src/main/maker-ipc/sessionEventStream.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionEventStream.ts
@@ -11,6 +11,7 @@ import {
enqueueDurableWrite,
flushAssistantBlock,
onAssistantTextEvent,
+ onAssistantAttemptFailure,
onAgentTaskUpdateEvent,
onThinkingEvent,
onToolResultEvent,
@@ -32,6 +33,10 @@ export function persistSessionStreamEvent(
const { event, eventAgentMeta } = prepared;
let persistId: string | undefined;
let resolvedContent: string | undefined;
+ if (event.source === 'codex' && event.turnScope !== 'background' &&
+ (event.type === 'error' || event.type === 'done')) {
+ onAssistantAttemptFailure(session.id, event.data);
+ }
if (event.type === 'text') {
const td = event.data as { text?: unknown; isFinal?: unknown; isFullText?: unknown } | null;
// A Host runtime-recovery notice (#4349) is not the worker's reply: it is
diff --git a/apps/desktop/src/main/messagePersistBroadcaster.ts b/apps/desktop/src/main/messagePersistBroadcaster.ts
index 2be06612c2..695c49a517 100644
--- a/apps/desktop/src/main/messagePersistBroadcaster.ts
+++ b/apps/desktop/src/main/messagePersistBroadcaster.ts
@@ -206,6 +206,47 @@ interface AssistantBlock {
}
const assistantBlocks = new Map<string, AssistantBlock>();
+/** Exact provider item → durable row links, scoped to the current product turn. */
+const assistantItemPersistIds = new Map<string, Map<string, string>>();
+
+/** Mark an SDK-proven failed sampling attempt without changing or deleting its prose. */
+export function onAssistantAttemptFailure(sessionId: string, data: unknown): void {
+ if (!data || typeof data !== 'object') return;
+ const failure = (data as { assistantAttemptFailure?: unknown }).assistantAttemptFailure;
+ if (!failure || typeof failure !== 'object') return;
+ const { threadId, turnId, attempt, agentMessageIds } = failure as Record<string, unknown>;
+ if (typeof threadId !== 'string' || typeof turnId !== 'string' ||
+ !Number.isSafeInteger(attempt) || typeof attempt !== 'number' || attempt < 1 ||
+ !Array.isArray(agentMessageIds)) return;
+ const links = assistantItemPersistIds.get(sessionId);
+ if (!links) return;
+ for (const itemId of agentMessageIds) {
+ if (typeof itemId !== 'string') continue;
+ const persistId = links.get(itemId);
+ if (!persistId) continue;
+ const message = (data as { message?: unknown }).message;
+ const marker = { threadId, turnId, attempt, itemId,
+ ...(typeof message === 'string' ? { error: redactSensitiveText(message) } : {}),
+ };
+ links.delete(itemId);
+ const block = assistantBlocks.get(sessionId);
+ if (block?.persistId === persistId) {
+ block.agentMeta = { ...block.agentMeta, failedSamplingAttempt: marker, turnCompleted: false };
+ flushAssistantBlock(sessionId);
+ } else {
+ enqueueWrite(`assistant_attempt_failed:${sessionId}:${persistId}`, async (ownerScope) => {
+ const patched = await patchMessageAgentMetaWithResult(sessionId, persistId, {
+ failedSamplingAttempt: marker,
+ turnCompleted: false,
+ });
+ if (patched) await broadcastMessageAgentMetaUpdate(sessionId, persistId, ownerScope);
+ });
+ }
+ if (lastTopLevelAssistantPersistIdBySession.get(sessionId) === persistId) {
+ lastTopLevelAssistantPersistIdBySession.delete(sessionId);
+ }
+ }
+}
/**
* 本轮 prompt 之前到达的非 final text(运行时就绪 / 重连期间的提示文本)会先建一个 block,
@@ -337,6 +378,7 @@ export function noteSessionClearBoundary(sessionId: string, clearedAt: string |
if (!Number.isFinite(parsed)) return;
const current = clearBoundaryBySession.get(sessionId);
if (current === undefined || parsed > current) {
+ assistantItemPersistIds.delete(sessionId);
clearSessionThinkingSnapshots(sessionId);
clearBoundaryBySession.set(sessionId, parsed);
sealedAssistantLateFinalBySession.delete(sessionId);
@@ -2040,6 +2082,7 @@ export function flushOrphanToolResults(sessionId: string, agentMeta: AgentMeta |
* + knownToolUseIds + lastAgentMeta。必须在 flushOrphanToolResults 之后调用。
*/
export function resetTurnPersistState(sessionId: string): void {
+ assistantItemPersistIds.delete(sessionId);
// Event-stream completion is not a persistence barrier. Thinking snapshots
// survive until their write succeeds or an explicit history/owner cleanup.
toolResultIdByToolUseId.delete(sessionId);
@@ -2107,6 +2150,24 @@ export function onAssistantTextEvent(
data: { text?: unknown; isFinal?: unknown; isFullText?: unknown; agentMessageId?: unknown; phase?: string; runtimeRecovery?: boolean },
agentMeta: AgentMeta | null,
turnScope?: 'turn' | 'background',
+): string | undefined {
+ const persistId = assembleAssistantTextEvent(sessionId, data, agentMeta, turnScope);
+ if (persistId && typeof data.agentMessageId === 'string' && turnScope !== 'background') {
+ let links = assistantItemPersistIds.get(sessionId);
+ if (!links) {
+ links = new Map();
+ assistantItemPersistIds.set(sessionId, links);
+ }
+ links.set(data.agentMessageId, persistId);
+ }
+ return persistId;
+}
+
+function assembleAssistantTextEvent(
+ sessionId: string,
+ data: { text?: unknown; isFinal?: unknown; isFullText?: unknown; agentMessageId?: unknown; phase?: string; runtimeRecovery?: boolean },
+ agentMeta: AgentMeta | null,
+ turnScope?: 'turn' | 'background',
): string | undefined {
if (typeof data.phase === 'string' || data.runtimeRecovery === true) {
agentMeta = { ...agentMeta, assistantPhase: data.runtimeRecovery === true ? 'commentary' : data.phase as string };
@@ -2849,6 +2910,7 @@ export function clearCodexPlanRowsForSession(sessionId: string): void {
}
export function clearSessionPersistState(sessionId: string): void {
+ assistantItemPersistIds.delete(sessionId);
clearSessionThinkingSnapshots(sessionId);
clearCodexPlanRowsForSession(sessionId);
assistantBlocks.delete(sessionId);
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
index b06068dfb9..7047b145a6 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
@@ -6858,6 +6858,31 @@ describe('makerChatStore text delta batching', () => {
expect(sentTexts).toEqual(['wait for preflight']);
});
+ // #6351: the row update must change the live reply and survive history reload;
+ // translator/persistence tests cannot observe this renderer projection.
+ it('projects failed sampling metadata into live text and reloaded history', async () => {
+ emitTextDelta('Opening from a failed attempt');
+ vi.advanceTimersByTime(32);
+ const persisted = serverMessage({
+ id: 'failed-row', clientId: 'assistant-1', sessionId: SESSION_ID, role: 'assistant',
+ content: 'Opening from a failed attempt', createdAt: new Date().toISOString(),
+ agentMeta: { failedSamplingAttempt: { threadId: 'thread', turnId: 'turn', attempt: 1, itemId: 'item' },
+ turnCompleted: false, turnCostUsd: 0.1 },
+ });
+ emitDbMessageCreated(persisted);
+ const assertFailure = () => {
+ const replies = makerChatStore.getSnapshot(SESSION_ID).messages.filter(message => message.role === 'assistant');
+ expect(replies).toHaveLength(1);
+ expect(replies[0]).toMatchObject({ content: persisted.content, failedSamplingAttempt: true, turnCompleted: false });
+ };
+ assertFailure();
+ makerChatStore.purgeSession(SESSION_ID);
+ vi.mocked(messageService.list).mockResolvedValueOnce([persisted]);
+ makerChatStore.ensureInitialMessages(SESSION_ID);
+ await flushPromises();
+ assertFailure();
+ });
+
it('hydrates existing runtime messages with authoritative DB-created timestamps', () => {
vi.setSystemTime(new Date('2026-06-15T00:00:30.000Z'));
emitTextDelta('draft');
diff --git a/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx b/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx
index 19e67cdb06..aaa7cadcc4 100644
--- a/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx
+++ b/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx
@@ -197,6 +197,7 @@ interface AssistantMessageProps {
showActionBar?: boolean;
/** 伙伴对话使用常显、无费用、无 Fork 的轻量消息操作栏。 */
simplifiedBotConversation?: boolean;
+ failedSamplingAttempt?: boolean;
botLearning?: unknown;
botTaskResults?: BotCollaborationMeta[];
/** Per-turn 费用 (USD) — 仅该轮最后一条 assistant 有值, action bar 时间旁显示。 */
@@ -226,6 +227,7 @@ export const AssistantMessage = memo(function AssistantMessage({
currentSessionId,
currentSessionTitle,
content,
+ failedSamplingAttempt,
isStreaming,
createdAt,
messageClientId,
@@ -336,6 +338,11 @@ export const AssistantMessage = memo(function AssistantMessage({
'text-[var(--msg-assistant-text)]',
)}
>
+ {failedSamplingAttempt && (
+ <div className="mb-1 text-13 font-normal leading-[18px]" style={{ color: 'var(--text-secondary)' }}>
+ {t('chat.failedSamplingAttempt')}
+ </div>
+ )}
{ghostRenderCard && messageClientId && !showOriginal ? (
// 出口钩子自绘:意识卡片替换气泡(净化后的静态 HTML,沙箱 iframe)。
// 复用 GhostToolCard(自带主机身份头 + 主题注入 + 沙箱),turn 级无
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index e6e752c53d..01000d69e9 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -6948,6 +6948,7 @@ const MessageItem = memo(function MessageItem({
turnUsageDetails={message.turnUsageDetails}
userTurnUsageDetails={userTurnUsageDetails}
modelMismatch={message.modelMismatch}
+ failedSamplingAttempt={message.failedSamplingAttempt}
ghostReplyPending={message.ghostReplyPending}
simplifiedBotConversation={simplifiedBotConversation}
botLearning={message.botLearning}
diff --git a/apps/desktop/src/renderer/components/chat/messageWorkGroups.ts b/apps/desktop/src/renderer/components/chat/messageWorkGroups.ts
index cb1d44d5ca..4ec5557229 100644
--- a/apps/desktop/src/renderer/components/chat/messageWorkGroups.ts
+++ b/apps/desktop/src/renderer/components/chat/messageWorkGroups.ts
@@ -159,6 +159,7 @@ export type RenderItem =
| WorkGroupRenderItem;
export function isCompletedAssistantMessage(message: ChatMessage): boolean {
+ if (message.failedSamplingAttempt) return false;
return (
message.turnCompleted === true ||
(message.turnMoney?.amount ?? 0) > 0 ||
@@ -240,6 +241,7 @@ function isDeliveryProseItem(it: RenderItem): boolean {
return (
it.type === 'message' &&
it.message.role === 'assistant' &&
+ !it.message.failedSamplingAttempt &&
!it.message.systemCardType &&
(Boolean(it.message.images?.length || it.message.files?.length) ||
isDeliveryProseText(it.message.content))
@@ -251,6 +253,7 @@ function isAssistantAnswerCandidate(it: RenderItem): it is MessageRenderItem {
return (
it.type === 'message' &&
it.message.role === 'assistant' &&
+ !it.message.failedSamplingAttempt &&
!it.message.systemCardType &&
it.message.content.trim().length > 0
);
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.ts
index 75aeee776f..9f5e43dc9b 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.ts
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.ts
@@ -22,6 +22,20 @@ const project = (items: RenderItem[], streaming: boolean) =>
simplifyBotRenderItems(groupWorkRuns(items, streaming), streaming);
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('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/desktop/src/renderer/features/bots/botConversationPresentation.ts b/apps/desktop/src/renderer/features/bots/botConversationPresentation.ts
index 6e89c38c47..f093819714 100644
--- a/apps/desktop/src/renderer/features/bots/botConversationPresentation.ts
+++ b/apps/desktop/src/renderer/features/bots/botConversationPresentation.ts
@@ -161,7 +161,7 @@ function projectWindow(
let sealedRun = false;
for (let index = expanded.length - 1; index >= 0; index -= 1) {
const item = expanded[index];
- if (!isProse(item) || !item.message.content.trim()) {
+ if (!isProse(item) || !item.message.content.trim() || item.message.failedSamplingAttempt) {
sealedRun = false;
continue;
}
@@ -169,6 +169,7 @@ function projectWindow(
if (sealedRun) sealedAnswers.add(item.message);
}
const isAddressedReply = (message: ChatMessage) => Boolean(message.content.trim())
+ && !message.failedSamplingAttempt
&& !(message.assistantPhase === 'commentary' && !message.explicitDelivery)
&& (message.assistantPhase === 'final_answer' || Boolean(message.sourceGroup)
|| Boolean(message.explicitDelivery) || isCompletedAssistantMessage(message) || sealedAnswers.has(message));
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index ad41f5aa96..c042e943e3 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -11033,6 +11033,7 @@
"verificationFailed": "Cindy couldn’t confirm whether the ChatGPT sign-in has recovered. Check again."
},
"chat": {
+ "failedSamplingAttempt": "This reply did not complete. Its content is for reference only.",
"jumpToBottom": "Jump to bottom",
"prevMessageJump": "Jump to previous prompt: {{preview}}",
"sessionLoading": "Loading task",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 1d9698633f..faa61d71ea 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -10986,6 +10986,7 @@
"verificationFailed": "ChatGPT ログインが復旧したか確認できませんでした。再確認してください。"
},
"chat": {
+ "failedSamplingAttempt": "この返信は完了しませんでした。内容は参考情報としてご覧ください。",
"jumpToBottom": "一番下へ移動",
"prevMessageJump": "前の質問へ移動:{{preview}}",
"sessionLoading": "セッションを読み込み中",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index f53245a63b..7ab02a2fa1 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -10986,6 +10986,7 @@
"verificationFailed": "ChatGPT 로그인이 복구되었는지 확인할 수 없습니다. 다시 확인해 주세요."
},
"chat": {
+ "failedSamplingAttempt": "완료되지 않은 답변입니다. 내용은 참고용으로만 확인해 주세요.",
"jumpToBottom": "맨 아래로 이동",
"prevMessageJump": "이전 질문으로 이동: {{preview}}",
"sessionLoading": "세션 불러오는 중",
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 8a639c6b87..64a67cf1ef 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -10986,6 +10986,7 @@
"verificationFailed": "暂时无法确认 ChatGPT 登录是否已恢复,请重新检测。"
},
"chat": {
+ "failedSamplingAttempt": "此回复未完成,内容仅供参考。",
"jumpToBottom": "跳到底部",
"prevMessageJump": "跳到上一条提问:{{preview}}",
"sessionLoading": "正在加载任务",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 00bffc8295..f5af9f0587 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -10986,6 +10986,7 @@
"verificationFailed": "暫時無法確認 ChatGPT 登入是否已恢復,請重新檢測。"
},
"chat": {
+ "failedSamplingAttempt": "此回覆未完成,內容僅供參考。",
"jumpToBottom": "跳到底部",
"prevMessageJump": "跳到上一則提問:{{preview}}",
"askUserQuestion": {
diff --git a/apps/desktop/src/renderer/lib/ccAgent.types.ts b/apps/desktop/src/renderer/lib/ccAgent.types.ts
index e69d2f4fcf..1d4e196a5f 100644
--- a/apps/desktop/src/renderer/lib/ccAgent.types.ts
+++ b/apps/desktop/src/renderer/lib/ccAgent.types.ts
@@ -105,6 +105,8 @@ export interface CcMeta {
botLearning?: import('@cindy/maker-shared/bot-learning').BotLearningReceipt[];
/** Provider text phase, retained to exclude commentary from notification previews. */
assistantPhase?: string;
+ /** Exact native sampling attempt that failed before response completion. Original text is retained. */
+ failedSamplingAttempt?: { threadId: string; turnId: string; attempt: number; itemId: string; error?: string };
uuid?: string;
parentUuid?: string;
/** Claude transcript chain parent. Do not confuse with parentUuid, which is parent_tool_use_id. */
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 3e2b427088..79ed7a2afd 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -524,6 +524,7 @@ export interface ChatMessage {
explicitDelivery?: boolean;
/** Provider phase survives live deltas and durable history projection. */
assistantPhase?: string;
+ failedSamplingAttempt?: boolean;
/** user 消息投递方式:普通新 turn 或运行中 steer。 */
delivery?: 'turn' | 'steer';
/** Hook 来源元数据(IM 平台 + 用户干净原文 + thread 上下文),UserMessage 据此渲染 Cindy 任务卡片。 */
@@ -19243,6 +19244,7 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {
content: typeof m.content === 'string' ? m.content : JSON.stringify(m.content),
...(m.role === 'assistant' ? { sourceGroup: readMessageSourceGroup(m.agentMeta) } : {}),
...(m.role === 'assistant' && typeof m.agentMeta?.assistantPhase === 'string' ? { assistantPhase: m.agentMeta.assistantPhase } : {}),
+ ...(m.role === 'assistant' && m.agentMeta?.failedSamplingAttempt ? { failedSamplingAttempt: true } : {}),
...(m.role === 'assistant' && m.agentMeta?.explicitDelivery === true ? { explicitDelivery: true } : {}),
...(m.role === 'assistant' ? { botLearning: m.agentMeta?.botLearning } : {}),
...(m.agentMeta?.botPrivateReply === true ? { botPrivateReply: true } : {}),
diff --git a/apps/mobile/src/__tests__/messageNormalize.test.ts b/apps/mobile/src/__tests__/messageNormalize.test.ts
index 9609e2b82e..44043ab98f 100644
--- a/apps/mobile/src/__tests__/messageNormalize.test.ts
+++ b/apps/mobile/src/__tests__/messageNormalize.test.ts
@@ -27,6 +27,20 @@ function message(patch: Partial<RemoteMessage> & Pick<RemoteMessage, 'id' | 'rol
}
describe('normalizeRemoteMessages', () => {
+ // #6351: historical failure metadata must survive remote normalization even
+ // when usage accounting is later attached to the same failed text row.
+ it('keeps failed sampling prose readable without inferring a completed reply from its cost', () => {
+ const output = normalizeRemoteMessages([
+ message({ id: 'failed', role: 'assistant', content: 'Opening from a failed attempt',
+ agentMeta: { failedSamplingAttempt: { threadId: 't', turnId: 'turn', attempt: 1, itemId: 'failed' },
+ turnCompleted: false, turnCostUsd: 0.1 } }),
+ message({ id: 'success', role: 'assistant', content: 'Successful reply', agentMeta: { turnCompleted: true } }),
+ ]);
+ expect(output[0]).toMatchObject({ body: 'Opening from a failed attempt', failedSamplingAttempt: true });
+ expect(output[0].turnCompleted).not.toBe(true);
+ expect(output[1]).toMatchObject({ body: 'Successful reply', turnCompleted: true });
+ expect(output[1].failedSamplingAttempt).toBeUndefined();
+ });
beforeAll(async () => {
await i18n.changeLanguage('zh-CN');
});
diff --git a/apps/mobile/src/i18n/locales/en/message.json b/apps/mobile/src/i18n/locales/en/message.json
index 11e25541c0..7756980bc3 100644
--- a/apps/mobile/src/i18n/locales/en/message.json
+++ b/apps/mobile/src/i18n/locales/en/message.json
@@ -9,6 +9,7 @@
}
},
"renderer": {
+ "failedSamplingAttempt": "This reply did not complete. Its content is for reference only.",
"moreActions": "More message actions",
"reply": "Reply",
"newMessagesToBottom": "New messages, jump to bottom",
diff --git a/apps/mobile/src/i18n/locales/ja/message.json b/apps/mobile/src/i18n/locales/ja/message.json
index 7f7afb9862..4ab767211c 100644
--- a/apps/mobile/src/i18n/locales/ja/message.json
+++ b/apps/mobile/src/i18n/locales/ja/message.json
@@ -9,6 +9,7 @@
}
},
"renderer": {
+ "failedSamplingAttempt": "この返信は完了しませんでした。内容は参考情報としてご覧ください。",
"moreActions": "その他のメッセージ操作",
"reply": "返信",
"newMessagesToBottom": "新着メッセージあり、最下部へ移動",
diff --git a/apps/mobile/src/i18n/locales/ko/message.json b/apps/mobile/src/i18n/locales/ko/message.json
index 9b0de33ecb..db93a0c533 100644
--- a/apps/mobile/src/i18n/locales/ko/message.json
+++ b/apps/mobile/src/i18n/locales/ko/message.json
@@ -9,6 +9,7 @@
}
},
"renderer": {
+ "failedSamplingAttempt": "완료되지 않은 답변입니다. 내용은 참고용으로만 확인해 주세요.",
"moreActions": "추가 메시지 작업",
"reply": "답장",
"newMessagesToBottom": "새 메시지, 맨 아래로 이동",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/message.json b/apps/mobile/src/i18n/locales/zh-CN/message.json
index 05b42d3606..4bc844d3ad 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/message.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/message.json
@@ -9,6 +9,7 @@
}
},
"renderer": {
+ "failedSamplingAttempt": "此回复未完成,内容仅供参考。",
"moreActions": "更多消息操作",
"reply": "回复",
"newMessagesToBottom": "有新消息,跳到底部",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/message.json b/apps/mobile/src/i18n/locales/zh-TW/message.json
index 0ab7268f95..3f6156e808 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/message.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/message.json
@@ -9,6 +9,7 @@
}
},
"renderer": {
+ "failedSamplingAttempt": "此回覆未完成,內容僅供參考。",
"moreActions": "更多訊息操作",
"reply": "回覆",
"newMessagesToBottom": "有新訊息,跳到底部",
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index d2eb1b7d86..2da2fde65d 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -3924,6 +3924,11 @@ function MessageBubble({
/>
) : null}
{attachmentStripNode}
+ {item.message.failedSamplingAttempt ? (
+ <Text style={styles.failedSamplingAttemptText}>
+ {t('message.renderer.failedSamplingAttempt')}
+ </Text>
+ ) : null}
{hasBubbleContent || (!attachmentStripNode && messageQuotes.length === 0) ? bubble : null}
{actions.companion && item.message.kind === 'assistant' && item.message.body.trim() ? (
<CompanionLearningFooter receipts={item.message.source.agentMeta?.botLearning}
@@ -8797,6 +8802,12 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
gap: 4,
maxWidth: '86%',
},
+ failedSamplingAttemptText: {
+ color: colors.textSecondary,
+ fontSize: typeScale.footnote,
+ lineHeight: lineHeight.caption,
+ fontWeight: '400',
+ },
modelMismatchText: {
color: colors.textTertiary,
flexShrink: 1,
diff --git a/apps/mobile/src/session/messageNormalize.ts b/apps/mobile/src/session/messageNormalize.ts
index b22e6f463a..3d3d4b3ef7 100644
--- a/apps/mobile/src/session/messageNormalize.ts
+++ b/apps/mobile/src/session/messageNormalize.ts
@@ -122,6 +122,7 @@ export interface NormalizedRemoteMessage {
isStreaming?: boolean;
/** Host 在 SDK done 边界写入;后台自动续跑时同一 turn 可有多次 seal,最后一次是最终答复。 */
turnCompleted?: boolean;
+ failedSamplingAttempt?: boolean;
turnMoney?: RemoteMoney;
/** 旧 Desktop 消息兼容字段。 */
turnCostUsd?: number;
@@ -604,6 +605,7 @@ export function normalizeRemoteMessages(
: {}),
...turnCost,
...readModelMismatch(message),
+ ...(message.role === 'assistant' && message.agentMeta?.failedSamplingAttempt ? { failedSamplingAttempt: true } : {}),
...(message.role === 'assistant' ? { sourceGroup: readMessageSourceGroup(message.agentMeta) } : {}),
...(message.role === 'assistant' && message.agentMeta?.explicitDelivery === true ? { explicitDelivery: true } : {}),
...(message.role === 'user' ? readAutomationOrigin(message) : {}),
@@ -1037,6 +1039,7 @@ export function remoteMessageCompletesTurn(
message: RemoteMessage,
turnCost = readTurnCost(message),
): boolean {
+ if (message.agentMeta?.failedSamplingAttempt) return false;
return message.role === 'assistant' && (
message.agentMeta?.turnCompleted === true
|| (turnCost.turnMoney?.amount ?? 0) > 0
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 4f4be5d6bd..f0fc737f08 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -175,6 +175,7 @@ import {
beginCodexGenerationTurn,
codexGenerationDurationMs,
finalizeCodexGenerationTurn,
+ finishCodexSamplingTurn,
pauseCodexGeneration,
resetCodexGenerationTiming,
resumeCodexGeneration,
@@ -6283,6 +6284,7 @@ assertRouteCurrent();
if (closed) return;
closed = true;
cancelInteractionContinuation(reason);
+ translatorRt.samplingSegments.clear();
resetCodexGenerationTiming(translatorRt);
resetUpstreamIdleForTurnEnd();
unregisterCodexMcpContext(threadId);
@@ -8603,6 +8605,7 @@ assertRouteCurrent();
resetCodexGenerationTiming(translatorRt);
turnDiffSnapshots.clear();
+ translatorRt.samplingSegments.clear();
proposedPlanText = null;
translatorRt.lastAuthErrorKey = null;
translatorRt.networkRetryNotice = null;
@@ -11152,6 +11155,9 @@ assertRouteCurrent();
// 到这里 = 这个 turn 的终态**要出 UI**, 逻辑 send 就此收口。墓碑压掉的那条路在上面
// 已经 return, 所以退避中的正常重投(死 turn 恒有墓碑)不会被误撤。
revokeOverloadRetryOnTerminalSettle(`turn_${turn.status}`);
+ const assistantAttemptFailure = finishCodexSamplingTurn(
+ translatorRt, params.threadId, turn.id, turn.status, turn.error,
+ );
if (turn.status === 'failed' || turn.status === 'interrupted') {
// 失败 / 中断的 plan turn 不发审批 — 半截计划没有审批意义, 循环就此结束。
@@ -11164,6 +11170,7 @@ assertRouteCurrent();
type: 'error',
data: {
...classified.data,
+ ...(assistantAttemptFailure ? { assistantAttemptFailure } : {}),
isTerminal: true,
},
source: 'codex',
@@ -11180,6 +11187,7 @@ assertRouteCurrent();
message: '任务执行失败(模型未返回错误详情)。',
isTerminal: true,
reason: 'turn-failed',
+ ...(assistantAttemptFailure ? { assistantAttemptFailure } : {}),
},
source: 'codex',
});
@@ -11189,6 +11197,7 @@ assertRouteCurrent();
data: {
type: 'codex/event/task_complete',
cancelled: turn.status === 'interrupted',
+ ...(assistantAttemptFailure ? { assistantAttemptFailure } : {}),
usage: codexDoneUsage,
raw: turn,
},
@@ -12967,6 +12976,7 @@ assertRouteCurrent();
translateErrorNotification(effectiveParams, eventQueue, {
rt: translatorRt,
log,
+ onSamplingAttemptFailed: () => assistantReplyByTurn.delete(effectiveParams.turnId),
tryTakeOverOverload: () => {
// 只接管 app-server 本来就不重试的容量拒绝(原始 willRetry !== true)。
// TurnRetryTracker 把持续 retry 升级成终态的那条路径不接管:那说明
@@ -13067,6 +13077,7 @@ assertRouteCurrent();
if (closed) return;
closed = true;
cancelInteractionContinuation('session_closed', true);
+ translatorRt.samplingSegments.clear();
resetCodexGenerationTiming(translatorRt);
clearReconnectStall();
resetUpstreamIdleForTurnEnd();
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.ts
new file mode 100644
index 0000000000..e4450d5c93
--- /dev/null
+++ b/packages/maker-core/src/agents/codex/sampling-retry.integration.test.ts
@@ -0,0 +1,161 @@
+/** #6351: real app-server + local Responses stream; no account, private logs or API spend.
+ * Unit notification fixtures cannot prove which notifications a truncated SSE
+ * response actually emits. The minimum input is one completed assistant item
+ * followed by EOF without response.completed; this opt-in integration tier
+ * covers the native process/socket boundary through CodexAgent.startSession.
+ */
+import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { createServer, type ServerResponse } from 'node:http';
+import { expect, it, vi } from 'vitest';
+import { CodexAgent } from './index.js';
+import type { Logger } from '../../interfaces/logger.js';
+import type { AgentEvent } from '../../types/events.js';
+
+const binaryPath = process.env.CINDY_TEST_CODEX_BINARY;
+const logger: Logger = {
+ trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child: () => logger,
+};
+
+it.skipIf(!binaryPath).each(['success', 'exhausted', 'stop', 'steer'] as const)(
+ 'attributes native sampling retries through %s and a later manual send', async (ending) => {
+ const root = await mkdtemp(path.join(tmpdir(), 'cindy-sampling-retry-'));
+ const home = path.join(root, 'codex-home');
+ const workingDir = path.join(root, 'workdir');
+ const requests: unknown[] = [];
+ const events: AgentEvent[] = [];
+ let heldResponse: ServerResponse | undefined;
+ let settled = 0;
+ let recover = false;
+ const sendEvent = (res: ServerResponse, event: { type: string; [key: string]: unknown }) =>
+ res.write('event: ' + event.type + '\ndata: ' + JSON.stringify(event) + '\n\n');
+ const complete = (res: ServerResponse, request: number) => {
+ sendEvent(res, { type: 'response.completed', response: { id: 'response-' + request,
+ usage: { input_tokens: 10, output_tokens: 5, total_tokens: 15 } } });
+ res.end();
+ };
+ const server = createServer(async (req, res) => {
+ if (req.method !== 'POST' || !req.url?.endsWith('/responses')) {
+ res.writeHead(404).end();
+ return;
+ }
+ const chunks: Buffer[] = [];
+ for await (const chunk of req) chunks.push(Buffer.from(chunk));
+ requests.push(JSON.parse(Buffer.concat(chunks).toString('utf8')));
+ const request = requests.length;
+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'close' });
+ sendEvent(res, { type: 'response.created', response: { id: 'response-' + 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')) {
+ complete(res, request);
+ } else if (request === 2 && (ending === 'stop' || ending === 'steer')) {
+ heldResponse = res;
+ } else {
+ // The assistant item is complete, but response.completed is absent.
+ // Native Codex must retry this sampling request rather than complete the turn.
+ res.end();
+ }
+ });
+ let agent: CodexAgent | undefined;
+ let pump: Promise<void> | undefined;
+ try {
+ await mkdir(home);
+ await mkdir(workingDir);
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const address = server.address();
+ if (!address || typeof address === 'string') throw new Error('missing local address');
+ await writeFile(path.join(home, 'config.toml'), [
+ 'model="fixture-model"', 'model_provider="fixture"',
+ 'cli_auth_credentials_store="ephemeral"', 'check_for_update_on_startup=false',
+ '[analytics]', 'enabled=false',
+ '[mcp_servers.cindy_memory]', 'command="false"', 'enabled=false',
+ '[model_providers.fixture]', 'name="Local retry fixture"',
+ 'base_url="http://127.0.0.1:' + address.port + '/v1"', 'wire_api="responses"',
+ 'requires_openai_auth=false', 'supports_websockets=false', 'request_max_retries=0', 'stream_max_retries=1',
+ ].join('\n'));
+ agent = new CodexAgent({ binaryPath: binaryPath!, logger, runtimeConfig: {},
+ resolveCodexLocalAuthPolicy: () => 'isolated',
+ prepareCodexExtraSpawnConfig: async () => ({ extraArgs: [], extraEnv: {}, codexProxyActive: true }),
+ auth: {
+ getState: async () => ({ authenticated: true }),
+ triggerLogin: async () => ({ authenticated: true }), logout: async () => {},
+ getAuthEnv: async () => ({ HOME: root, USERPROFILE: root, APPDATA: root, LOCALAPPDATA: root,
+ CODEX_HOME: home, TMPDIR: root, OPENAI_API_KEY: '', CODEX_API_KEY: '',
+ HTTP_PROXY: 'http://127.0.0.1:1', HTTPS_PROXY: 'http://127.0.0.1:1',
+ ALL_PROXY: 'http://127.0.0.1:1', NO_PROXY: '127.0.0.1,localhost' }),
+ },
+ });
+ const handle = await agent.startSession({ sessionId: 'sampling-fixture', providerId: 'cprov-fixture',
+ model: 'fixture-model', workingDir, makerMemoryEnabled: false });
+ pump = (async () => {
+ for await (const event of handle.events()) {
+ events.push(event);
+ const data = event.data as { isRunning?: boolean };
+ if (event.type === 'done' || (event.type === 'status' && data.isRunning === false)) settled++;
+ }
+ })();
+ await handle.send({ type: 'user', content: 'Introduce yourself once.' }, { throwOnStartFailure: true });
+ if (ending === 'stop' || ending === 'steer') {
+ await vi.waitFor(() => expect(events.some(event => event.type === 'text' &&
+ (event.data as { agentMessageId?: string }).agentMessageId === 'answer-2')).toBe(true), { timeout: 10_000 });
+ expect(settled).toBe(0);
+ if (ending === 'stop') await handle.abort();
+ else {
+ await handle.steer({ type: 'user', content: 'Also include the word steered.' });
+ complete(heldResponse!, 2);
+ }
+ }
+ await vi.waitFor(() => expect(settled).toBeGreaterThan(0), { timeout: 15_000 });
+ // A terminal native error may settle without a synthetic done. Steering
+ // adds a successful sampling request in the same turn after the held one.
+ if (ending !== 'exhausted') {
+ await vi.waitFor(() => expect(events.some(event => event.type === 'done')).toBe(true));
+ }
+ expect(requests).toHaveLength(ending === 'steer' ? 3 : 2);
+ if (ending === 'exhausted') {
+ expect(events.some(event => event.type === 'error' &&
+ (event.data as { isTerminal?: boolean }).isTerminal === true)).toBe(true);
+ }
+ if (ending === 'stop') {
+ expect(events.some(event => event.type === 'done' &&
+ (event.data as { cancelled?: boolean }).cancelled === true)).toBe(true);
+ }
+ const failures = events.flatMap(event => {
+ const data = event.data as { assistantAttemptFailure?: { agentMessageIds: string[]; turnId: string } };
+ return data?.assistantAttemptFailure ? [data.assistantAttemptFailure] : [];
+ });
+ expect(failures.flatMap(failure => failure.agentMessageIds)).toContain('answer-1');
+ expect(new Set(failures.map(failure => failure.turnId)).size).toBe(1);
+ if (ending === 'exhausted' || ending === 'stop') {
+ expect(failures.flatMap(failure => failure.agentMessageIds)).toContain('answer-2');
+ } else {
+ expect(failures.flatMap(failure => failure.agentMessageIds)).not.toContain('answer-2');
+ }
+ expect(events.filter(event => event.type === 'text').map(event =>
+ (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);
+ const failureCount = failures.length;
+ recover = true;
+ const boundary = events.length;
+ await handle.send({ type: 'user', content: 'Continue.' }, { throwOnStartFailure: true });
+ await vi.waitFor(() => expect(events.slice(boundary).some(event => event.type === 'done')).toBe(true),
+ { timeout: 10_000 });
+ expect(events.slice(boundary).some(event =>
+ (event.data as { assistantAttemptFailure?: unknown })?.assistantAttemptFailure)).toBe(false);
+ expect(failureCount).toBeGreaterThan(0);
+ await handle.close();
+ await pump;
+ } finally {
+ heldResponse?.destroy();
+ await agent?.dispose();
+ await pump;
+ server.closeAllConnections();
+ if (server.listening) await new Promise<void>((resolve) => server.close(() => resolve()));
+ await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
+ }
+ }, 45_000,
+);
diff --git a/packages/maker-core/src/agents/codex/translator.test.ts b/packages/maker-core/src/agents/codex/translator.test.ts
index 3b96eadcac..e285d1e32d 100644
--- a/packages/maker-core/src/agents/codex/translator.test.ts
+++ b/packages/maker-core/src/agents/codex/translator.test.ts
@@ -24,7 +24,9 @@ import {
beginCodexGenerationTurn,
codexGenerationDurationMs,
finalizeCodexGenerationTurn,
+ finishCodexSamplingTurn,
pauseCodexGeneration,
+ resetCodexGenerationTiming,
resumeCodexGeneration,
} from './translator.js';
import type { CodexRuntimeState } from './translator.js';
@@ -81,6 +83,58 @@ async function collect(queue: AsyncQueue<AgentEvent>): Promise<AgentEvent[]> {
}
describe('Codex assistant text streaming contract', () => {
+ it.each(['completed', 'failed', 'interrupted'])('isolates failed sampling items when the retry turn is %s', async (status) => {
+ const rt = newCodexRuntimeState();
+ const q = createAsyncQueue<AgentEvent>();
+ const ctx = makeCtx(rt);
+ const delta = (turnId: string, itemId: string) => translateAgentMessageDelta({
+ threadId: 't1', turnId, itemId, delta: 'Opening',
+ }, q, ctx);
+ delta('turn-a', 'first');
+ delta('turn-b', 'other-turn');
+ translateErrorNotification(makeParams({ willRetry: true, message: 'stream disconnected',
+ codexErrorInfo: { responseStreamDisconnected: {} } }), q, ctx);
+ delta('turn-a', 'retry');
+ expect(finishCodexSamplingTurn(rt, 't1', 'turn-a', status)).toEqual(status === 'completed'
+ ? undefined : { threadId: 't1', turnId: 'turn-a', attempt: 2, agentMessageIds: ['retry'] });
+ expect(finishCodexSamplingTurn(rt, 't1', 'turn-a', status)).toBeUndefined();
+ translateErrorNotification(makeParams({ turnId: 'turn-b', willRetry: false, message: 'stream disconnected' }), q, ctx);
+ const failures = (await collect(q)).filter(event => event.type === 'error').map(event =>
+ (event.data as { assistantAttemptFailure?: { agentMessageIds: string[] } }).assistantAttemptFailure?.agentMessageIds);
+ expect(failures).toEqual([['first'], ['other-turn']]);
+ resetCodexGenerationTiming(rt);
+ });
+ // #6351: item/completed is not response completion. Existing text-delta tests
+ // never inject a stream failure after an assistant item has already completed.
+ it('attributes a failed sampling segment without discarding earlier tool progress or final retry output', async () => {
+ const rt = newCodexRuntimeState();
+ const q = createAsyncQueue<AgentEvent>();
+ const ctx = makeCtx(rt);
+ const complete = (id: string, text: string, phase: 'commentary' | 'final_answer') =>
+ translateItemNotification('completed', { threadId: 't1', turnId: 'turn-a',
+ item: { type: 'agentMessage', id, text, phase } }, q, ctx);
+ complete('progress', 'Checking the workspace', 'commentary');
+ translateItemNotification('completed', { threadId: 't1', turnId: 'turn-a',
+ item: { type: 'commandExecution', id: 'tool', command: 'pwd', cwd: '/repo',
+ status: 'completed', aggregatedOutput: '/repo', exitCode: 0 } }, q, ctx);
+ complete('failed-commentary', 'Preparing the answer', 'commentary');
+ complete('failed-answer', 'Hello from attempt one', 'final_answer');
+ 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');
+ const events = await collect(q);
+ expect(events.filter(event => event.type === 'text')).toHaveLength(4);
+ expect(events.find(event => event.type === 'error')).toMatchObject({
+ data: { isTerminal: false, willRetry: true, assistantAttemptFailure: {
+ threadId: 't1', turnId: 'turn-a', attempt: 1,
+ agentMessageIds: ['failed-commentary', 'failed-answer'],
+ } },
+ });
+ expect(events.some(event => event.type === 'done')).toBe(false);
+ resetCodexGenerationTiming(rt);
+ });
+
it('uses dedicated deltas for live text, dedupes item snapshots, and keeps completed as final calibration', async () => {
const rt = newCodexRuntimeState();
const q = createAsyncQueue<AgentEvent>();
diff --git a/packages/maker-core/src/agents/codex/translator.ts b/packages/maker-core/src/agents/codex/translator.ts
index 726a47dc63..f6f3d86f92 100644
--- a/packages/maker-core/src/agents/codex/translator.ts
+++ b/packages/maker-core/src/agents/codex/translator.ts
@@ -74,6 +74,8 @@ import type {
// 但因为 reasoning text 现在是数组 join 出来的, reasoningTextLen 跟踪 join 后总长。
export interface CodexRuntimeState {
+ /** Text since the last completed tool belongs to the current sampling request. */
+ samplingSegments: Map<string, { threadId: string; turnId: string; attempt: number; itemIds: Set<string> }>;
/** item.id → reasoning 第一次 emit 'start' 的时间 (Date.now ms)。 */
reasoningStartedAt: Map<string, number>;
/** item.id → reasoning 已 emit 文本字符长度 (上次 join 后总长)。 */
@@ -130,6 +132,7 @@ export interface CodexRuntimeState {
export function newCodexRuntimeState(): CodexRuntimeState {
return {
+ samplingSegments: new Map(),
reasoningStartedAt: new Map(),
reasoningTextLen: new Map(),
itemTextLen: new Map(),
@@ -350,6 +353,8 @@ interface TranslatorLog {
export interface CodexTranslateContext {
rt: CodexRuntimeState;
log: TranslatorLog;
+ /** A failed sample cannot remain the adapter's successful final-text fallback. */
+ onSamplingAttemptFailed?: () => void;
/**
* Maker Memory flush 观察器 — codex contextCompaction completed 时调,
* controller 重置 fired 阈值 (compact 后 context 又有空间, 可重新触发)。
@@ -380,6 +385,51 @@ export interface CodexTranslateContext {
// ── 主入口: 三个 item.* notification 的统一分发 ────────────────────────────────
type ItemPhase = 'started' | 'updated' | 'completed';
+// Host-executed tool results prove the preceding response was accepted. Built-in
+// search/image items can complete inside the still-open SSE response and do not.
+const SAMPLING_ACCEPTED_TOOL_TYPES = new Set([
+ 'commandExecution', 'mcpToolCall', 'dynamicToolCall', 'collabAgentToolCall', 'fileChange',
+]);
+
+function isSamplingStreamFailure(error: ClassifiedCodexError): boolean {
+ return error.errorInfoTag === 'responseStreamDisconnected' ||
+ error.errorInfoTag === 'responseTooManyFailedAttempts' ||
+ /stream disconnected|retrying sampling request|stream ended before.*response\.completed/i.test(error.message);
+}
+
+function samplingSegment(rt: CodexRuntimeState, threadId: string, turnId: string) {
+ const key = JSON.stringify([threadId, turnId]);
+ let segment = rt.samplingSegments.get(key);
+ if (!segment) {
+ segment = { threadId, turnId, attempt: 1, itemIds: new Set<string>() };
+ rt.samplingSegments.set(key, segment);
+ }
+ return segment;
+}
+
+/** Exact identities, never prose similarity or final_answer-only filtering (#6351). */
+function failSamplingSegment(rt: CodexRuntimeState, threadId: string, turnId: string) {
+ const segment = rt.samplingSegments.get(JSON.stringify([threadId, turnId]));
+ if (!segment) return undefined;
+ const agentMessageIds = [...segment.itemIds];
+ segment.itemIds.clear();
+ const attempt = segment.attempt++;
+ return agentMessageIds.length ? { threadId, turnId, attempt, agentMessageIds } : undefined;
+}
+
+/** A stopped retry remains auditable; a successful turn never marks its last reply failed. */
+export function finishCodexSamplingTurn(
+ rt: CodexRuntimeState, threadId: string, turnId: string, status: string,
+ error?: ErrorNotification['params']['error'] | null,
+) {
+ const key = JSON.stringify([threadId, turnId]);
+ const segment = rt.samplingSegments.get(key);
+ const failure = status !== 'completed' && segment &&
+ (segment.attempt > 1 || (error && isSamplingStreamFailure(classifyCodexError(error))))
+ ? failSamplingSegment(rt, threadId, turnId) : undefined;
+ rt.samplingSegments.delete(key);
+ return failure;
+}
export function translateItemNotification(
phase: ItemPhase,
@@ -400,6 +450,14 @@ export function translateItemNotification(
ctx.log.warn('item missing type field', { phase, itemKeys: Object.keys(item) });
return;
}
+ if (itemType === 'agentMessage') {
+ samplingSegment(ctx.rt, notification.threadId, notification.turnId).itemIds.add(item.id);
+ } else if (phase === 'completed' &&
+ SAMPLING_ACCEPTED_TOOL_TYPES.has(itemType)) {
+ // Tool results prove earlier generation was accepted. Its commentary and
+ // side effects must not be invalidated by a later sampling request failing.
+ ctx.rt.samplingSegments.delete(JSON.stringify([notification.threadId, notification.turnId]));
+ }
noteCodexGenerationBoundary(
ctx.rt,
phase,
@@ -562,12 +620,18 @@ export function translateErrorNotification(
ctx: CodexTranslateContext,
): void {
const classified = classifyCodexError(params.error);
- const message = classified.message;
const safeMessage = classified.message;
const errorStatus = classified.errorStatus;
const isCapacityError = classified.isCapacityError;
- const errorInfoTag = classified.errorInfoTag;
const safeErrorData = classified.data;
+ const segment = ctx.rt.samplingSegments.get(JSON.stringify([params.threadId, params.turnId]));
+ const streamFailed = isSamplingStreamFailure(classified) || (!params.willRetry && (segment?.attempt ?? 1) > 1);
+ const assistantAttemptFailure = streamFailed
+ ? failSamplingSegment(ctx.rt, params.threadId, params.turnId) : undefined;
+ if (assistantAttemptFailure) {
+ Object.assign(safeErrorData, { assistantAttemptFailure });
+ ctx.onSamplingAttemptFailed?.();
+ }
// willRetry=true 的暂时错误 (transient API blip / 5xx blip), server 自己会重试 — 默认
// 不 emit error event 给 UI,否则会把瞬时错误暴露成用户可见失败。**但** auth 缺失
// (401/Unauthorized/Missing bearer) 是 daemon 怎么 retry 也不可能自愈的 —— 必须
@@ -581,7 +645,7 @@ export function translateErrorNotification(
ctx.log.warn('codex error (will retry)', { message: safeMessage, threadId: params.threadId, turnId: params.turnId });
// Codex 自带明确的有限重连进度时,每档都透出,让 UI 从 1/5 持续更新到 5/5。
// 这是非终止状态:turn 仍由 app-server 继续,不结束也不另起一次不安全的请求重放。
- if (parseReconnectAttemptMessage(safeMessage)) {
+ if (assistantAttemptFailure || parseReconnectAttemptMessage(safeMessage)) {
queue.push({
type: 'error',
data: { ...safeErrorData, isTerminal: false, willRetry: true },
@@ -690,6 +754,9 @@ export function translateErrorNotification(
},
source: 'codex',
});
+ if (!params.willRetry) {
+ ctx.rt.samplingSegments.delete(JSON.stringify([params.threadId, params.turnId]));
+ }
}
export function translatePlanUpdatedNotification(
@@ -1162,6 +1229,7 @@ export function translateAgentMessageDelta(
ctx: CodexTranslateContext,
): void {
if (!params.delta) return;
+ samplingSegment(ctx.rt, params.threadId, params.turnId).itemIds.add(params.itemId);
const currentText = ctx.rt.itemRawText.get(params.itemId) ?? '';
const previousDeltaText = ctx.rt.itemDeltaText.get(params.itemId) ?? '';
let rawText: string;