Skip to content

Commit 370f306

Browse files
committed
fix(ai): retain visible details through phase tagging
1 parent 2aa5e52 commit 370f306

4 files changed

Lines changed: 84 additions & 4 deletions

File tree

‎packages/ai/src/provider-transport-parity.test.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,19 @@ const openAiSplitVisibleReasoningDetailsChunks = [
248248
makeOpenAiChunk({}, "stop"),
249249
] satisfies OpenAIChunk[];
250250

251+
const openAiVisibleDetailBeforeInterruptedContentChunks = [
252+
makeOpenAiChunk({
253+
reasoning_details: [{ type: "response.output_text", text: "Visible first." }],
254+
}),
255+
makeOpenAiChunk({
256+
reasoning_details: [{ type: "reasoning.text", text: " Hidden second." }],
257+
}),
258+
makeOpenAiChunk({ content: "Interim." }),
259+
makeOpenAiChunk({ reasoning_content: "Hidden fourth." }),
260+
makeOpenAiChunk({ content: "Final." }),
261+
makeOpenAiChunk({}, "stop"),
262+
] satisfies OpenAIChunk[];
263+
251264
const openAiTrailingReasoningChunks = [
252265
makeOpenAiChunk({ reasoning_content: "First thought." }),
253266
makeOpenAiChunk({ content: "Answer." }),
@@ -723,4 +736,44 @@ describe("provider and transport observable parity fixtures", () => {
723736
}
724737
}
725738
});
739+
740+
it("preserves earlier visible details when later ordinary content is interrupted", async () => {
741+
for (const implementation of ["provider", "transport"] as const) {
742+
const result = await runOpenAi(
743+
implementation,
744+
"success",
745+
openAiVisibleDetailBeforeInterruptedContentChunks,
746+
true,
747+
openRouterModel,
748+
);
749+
750+
expect(result.terminal.content).toEqual([
751+
{
752+
type: "text",
753+
text: "Visible first.",
754+
textSignature: '{"v":1,"id":"final-answer-0","phase":"final_answer"}',
755+
},
756+
{
757+
type: "thinking",
758+
thinking: " Hidden second.",
759+
thinkingSignature: "reasoning_details",
760+
},
761+
{
762+
type: "text",
763+
text: "Interim.",
764+
textSignature: '{"v":1,"id":"commentary-0","phase":"commentary"}',
765+
},
766+
{
767+
type: "thinking",
768+
thinking: "Hidden fourth.",
769+
thinkingSignature: "reasoning_content",
770+
},
771+
{
772+
type: "text",
773+
text: "Final.",
774+
textSignature: '{"v":1,"id":"final-answer-1","phase":"final_answer"}',
775+
},
776+
]);
777+
}
778+
});
726779
});

‎packages/ai/src/providers/openai-completions.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,7 @@ export const streamOpenAICompletions: StreamFunction<
214214
// *_end event is emitted exactly once.
215215
const finishedBlocks = new Set<StreamingBlock>();
216216
const contentIndices = new WeakMap<StreamingBlock, number>();
217+
let explicitVisibleTextBlocks: Set<TextContent> | undefined;
217218
const appendBlock = (block: StreamingBlock) => {
218219
contentIndices.set(block, blocks.length);
219220
blocks.push(block);
@@ -276,6 +277,9 @@ export const streamOpenAICompletions: StreamFunction<
276277
if (!textBlock) {
277278
textBlock = { type: "text", text: "" };
278279
textBlockSource = source;
280+
if (source === "reasoning_detail") {
281+
(explicitVisibleTextBlocks ??= new Set()).add(textBlock);
282+
}
279283
appendBlock(textBlock);
280284
stream.push({
281285
type: "text_start",
@@ -639,7 +643,11 @@ export const streamOpenAICompletions: StreamFunction<
639643
);
640644
}
641645
if (output.stopReason !== "toolUse" && confirmedInterruptedTextBlock) {
642-
tagInterruptedTextPhases(output.content, confirmedInterruptedTextBlock);
646+
tagInterruptedTextPhases(
647+
output.content,
648+
confirmedInterruptedTextBlock,
649+
explicitVisibleTextBlocks,
650+
);
643651
}
644652
// Tool completion is irreversible: confirm the terminal before closing
645653
// blocks, then preserve their original text/thinking/tool event order.

‎packages/ai/src/transports/openai-completions-stream.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,7 @@ export async function processCompletionsStream(
116116
const toolCallBlocksById = new Map<string, ToolCallBlock>();
117117
const provisionalCommentaryTags: PendingCommentaryTags = new Map();
118118
const toolCallBlockIndices = new WeakMap<ToolCallBlock, number>();
119+
let explicitVisibleTextBlocks: Set<TextBlock> | undefined;
119120
const normalizeToolCallDeltas = createOpenAICompletionsToolCallDeltaNormalizer();
120121
let sawStopFinishReason = false;
121122
let sawNativeToolCallDelta = false;
@@ -176,6 +177,9 @@ export async function processCompletionsStream(
176177
if (!currentBlock || currentBlock.type !== "text") {
177178
currentBlock = { type: "text", text: "" };
178179
currentTextSource = source;
180+
if (source === "reasoning_detail") {
181+
(explicitVisibleTextBlocks ??= new Set()).add(currentBlock);
182+
}
179183
output.content.push(currentBlock);
180184
pushStreamEvent({ type: "text_start", contentIndex: blockIndex(), partial: output });
181185
}
@@ -585,7 +589,11 @@ export async function processCompletionsStream(
585589
output.stopReason !== "error" &&
586590
output.stopReason !== "aborted"
587591
) {
588-
tagInterruptedTextPhases(output.content, confirmedInterruptedTextBlock);
592+
tagInterruptedTextPhases(
593+
output.content,
594+
confirmedInterruptedTextBlock,
595+
explicitVisibleTextBlocks,
596+
);
589597
}
590598
if (output.stopReason !== "toolUse") {
591599
clearPendingCommentaryText(provisionalCommentaryTags);

‎packages/ai/src/utils/assistant-text-phase.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ type AssistantTextPhaseBlock = {
66

77
export type PendingCommentaryTags = Map<AssistantTextPhaseBlock, string>;
88

9+
const EMPTY_ASSISTANT_TEXT_BLOCK_SET: ReadonlySet<unknown> = new Set();
10+
911
function isAssistantTextPhaseBlock(block: unknown): block is AssistantTextPhaseBlock {
1012
if (!block || typeof block !== "object") {
1113
return false;
@@ -47,6 +49,7 @@ export function tagPendingCommentaryText(content: ReadonlyArray<unknown>): Pendi
4749
export function tagInterruptedTextPhases(
4850
content: ReadonlyArray<unknown>,
4951
interruptedText: unknown,
52+
preservedVisibleText: ReadonlySet<unknown> = EMPTY_ASSISTANT_TEXT_BLOCK_SET,
5053
): void {
5154
const interruptedTextIndex = content.indexOf(interruptedText);
5255
if (interruptedTextIndex === -1) {
@@ -61,8 +64,16 @@ export function tagInterruptedTextPhases(
6164
if (finalAnswerIndex === -1) {
6265
return;
6366
}
64-
tagUnphasedText(content.slice(0, finalAnswerIndex), "commentary", "commentary");
65-
tagUnphasedText(content.slice(finalAnswerIndex), "final_answer", "final-answer");
67+
tagUnphasedText(
68+
content.slice(0, finalAnswerIndex).filter((block) => !preservedVisibleText.has(block)),
69+
"commentary",
70+
"commentary",
71+
);
72+
tagUnphasedText(
73+
content.filter((block, index) => index >= finalAnswerIndex || preservedVisibleText.has(block)),
74+
"final_answer",
75+
"final-answer",
76+
);
6677
}
6778

6879
/** Prevents unresolved completion text from becoming a fallback answer after stream failure. */

0 commit comments

Comments
 (0)