Skip to content

Commit 79701df

Browse files
authored
fix: speed up streamed assistant output (#122206)
* fix: speed up streamed assistant output * fix: preserve plan stream invalidation
1 parent 7fe75ac commit 79701df

8 files changed

Lines changed: 258 additions & 129 deletions

File tree

‎extensions/openai/openai-provider.test.ts‎

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2309,7 +2309,7 @@ describe("buildOpenAIProvider", () => {
23092309
});
23102310

23112311
expectFields(extraParams, {
2312-
transport: "auto",
2312+
transport: "sse",
23132313
});
23142314
expect(result.payload.store).toBe(true);
23152315
expect(result.payload.context_management).toEqual([
@@ -2616,14 +2616,40 @@ describe("buildOpenAIProvider", () => {
26162616
expect(allowedHostedToolTypes).toEqual(new Set());
26172617
});
26182618

2619-
it("preserves explicit OpenAI responses transport overrides", () => {
2619+
it("defaults direct OpenAI API-key traffic to SSE and preserves explicit WebSocket", () => {
26202620
const provider = buildOpenAIProvider();
26212621

26222622
const explicit = {
26232623
transport: "websocket",
26242624
fastMode: true,
26252625
};
26262626

2627+
expect(
2628+
provider.prepareExtraParams?.({
2629+
provider: "openai",
2630+
modelId: "gpt-5.4",
2631+
model: {
2632+
api: "openai-responses",
2633+
provider: "openai",
2634+
id: "gpt-5.4",
2635+
baseUrl: "https://api.openai.com/v1",
2636+
},
2637+
config: {
2638+
models: {
2639+
providers: {
2640+
openai: {
2641+
api: "openai-responses",
2642+
auth: "api-key",
2643+
baseUrl: "https://api.openai.com/v1",
2644+
models: [],
2645+
},
2646+
},
2647+
},
2648+
},
2649+
extraParams: { effort: "high" },
2650+
} as never),
2651+
).toEqual({ effort: "high", transport: "sse" });
2652+
26272653
expect(
26282654
provider.prepareExtraParams?.({
26292655
provider: "openai",
@@ -2633,7 +2659,7 @@ describe("buildOpenAIProvider", () => {
26332659
).toBe(explicit);
26342660
});
26352661

2636-
it("does not infer Codex transport from an unselected OAuth profile", () => {
2662+
it("uses SSE for an unselected OAuth profile and native defaults for a Codex route", () => {
26372663
const provider = buildOpenAIProvider();
26382664

26392665
expect(
@@ -2654,7 +2680,7 @@ describe("buildOpenAIProvider", () => {
26542680
} as never),
26552681
).toEqual({
26562682
effort: "high",
2657-
transport: "auto",
2683+
transport: "sse",
26582684
});
26592685
expect(
26602686
provider.prepareExtraParams?.({

‎extensions/openai/openai-provider.ts‎

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1077,12 +1077,7 @@ export function buildOpenAIProvider(): ProviderPlugin {
10771077
(normalizeProviderId(ctx.provider) === PROVIDER_ID &&
10781078
(!providerConfig?.baseUrl || isOpenAIHttpsApiBaseUrl(providerConfig.baseUrl)) &&
10791079
resolveConfiguredProviderAuthTransport(providerConfig) === "codex");
1080-
const responsesBaseUrl = ctx.model?.baseUrl ?? providerConfig?.baseUrl;
1081-
const useNativeResponsesTransport =
1082-
useCodexTransport || !responsesBaseUrl || isOpenAIHttpsApiBaseUrl(responsesBaseUrl);
1083-
return (
1084-
useNativeResponsesTransport ? nativeResponsesHooks : responsesHooks
1085-
).prepareExtraParams?.(ctx);
1080+
return (useCodexTransport ? nativeResponsesHooks : responsesHooks).prepareExtraParams?.(ctx);
10861081
},
10871082
resolveUsageAuth: codexHooks.resolveUsageAuth,
10881083
fetchUsageSnapshot: codexHooks.fetchUsageSnapshot,

‎src/gateway/server-chat-state.ts‎

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ type ChatRunToolRecipientState = {
104104
finalizedAt?: number;
105105
};
106106

107-
type PendingChatDeltaFlush = {
107+
type PendingLiveTextFlush = {
108108
timer: NodeJS.Timeout;
109109
flush: () => void;
110110
};
@@ -133,7 +133,7 @@ type ChatRunRecord = {
133133

134134
type InternalChatRunRecord = ChatRunRecord & {
135135
/** Fixed-deadline trailing wake-up owned by this run's buffered state. */
136-
pendingDeltaFlush?: PendingChatDeltaFlush;
136+
pendingTextFlushes?: Partial<Record<"chat" | "agent", PendingLiveTextFlush>>;
137137
};
138138

139139
type ChatRunRecordStore = {
@@ -167,13 +167,12 @@ function internalChatRunRecord(record: ChatRunRecord): InternalChatRunRecord {
167167
return record;
168168
}
169169

170-
function clearPendingChatDeltaFlush(record: ChatRunRecord): void {
170+
function clearPendingLiveTextFlushes(record: ChatRunRecord): void {
171171
const internal = internalChatRunRecord(record);
172-
if (!internal.pendingDeltaFlush) {
173-
return;
172+
for (const pending of Object.values(internal.pendingTextFlushes ?? {})) {
173+
clearTimeout(pending.timer);
174174
}
175-
clearTimeout(internal.pendingDeltaFlush.timer);
176-
delete internal.pendingDeltaFlush;
175+
delete internal.pendingTextFlushes;
177176
}
178177

179178
export type ChatRunRegistry = {
@@ -297,14 +296,14 @@ export function createChatRunState(): ChatRunState {
297296
delete record.deltaSentAt;
298297
delete record.deltaLastBroadcastLen;
299298
delete record.deltaLastBroadcastText;
300-
clearPendingChatDeltaFlush(record);
299+
clearPendingLiveTextFlushes(record);
301300
delete record.agentText;
302301
store.releaseIfEmpty(runId);
303302
};
304303

305304
const clear = () => {
306305
for (const record of store.runs.values()) {
307-
clearPendingChatDeltaFlush(record);
306+
clearPendingLiveTextFlushes(record);
308307
}
309308
store.runs.clear();
310309
};

‎src/gateway/server-chat.agent-events.test.ts‎

Lines changed: 86 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -720,14 +720,14 @@ describe("agent event handler", () => {
720720
expect(agentBroadcastCalls(broadcast)).toHaveLength(1);
721721
});
722722

723-
it("coalesces assistant agent events under the chat delta throttle", () => {
723+
it("coalesces assistant agent events inside one live-text pacing window", () => {
724724
let now = 10_000;
725725
const nowSpy = vi.spyOn(Date, "now").mockImplementation(() => now);
726726
const { broadcast, nodeSendToSession, chatRunState, handler } = createHarness();
727727
registerNamedChatRun(chatRunState, "agent-throttle");
728728

729729
for (let i = 0; i < 5; i += 1) {
730-
now = 10_000 + i * 20;
730+
now = 10_000 + i * 10;
731731
emitAgentEvent(
732732
handler,
733733
"run-agent-throttle",
@@ -752,22 +752,69 @@ describe("agent event handler", () => {
752752
nowSpy.mockRestore();
753753
});
754754

755+
it("flushes trailing assistant agent text at the fixed pacing deadline", () => {
756+
vi.useFakeTimers();
757+
let now = 15_000;
758+
const nowSpy = vi.spyOn(Date, "now").mockImplementation(() => now);
759+
const { broadcast, chatRunState, handler } = createHarness();
760+
registerNamedChatRun(chatRunState, "agent-trailing");
761+
762+
emitAgentEvent(handler, "run-agent-trailing", "assistant", {
763+
text: "Hello",
764+
delta: "Hello",
765+
});
766+
now = 15_020;
767+
emitAgentEvent(
768+
handler,
769+
"run-agent-trailing",
770+
"assistant",
771+
{ text: "Hello world", delta: " world" },
772+
{ seq: 2 },
773+
);
774+
775+
expect(
776+
agentBroadcastCalls(broadcast).map(([, payload]) => ({
777+
seq: (payload as { seq?: number }).seq,
778+
text: (payload as { data?: { text?: string } }).data?.text,
779+
})),
780+
).toEqual([{ seq: 1, text: "Hello" }]);
781+
782+
now = 15_074;
783+
vi.advanceTimersByTime(54);
784+
expect(agentBroadcastCalls(broadcast)).toHaveLength(1);
785+
786+
now = 15_075;
787+
vi.advanceTimersByTime(1);
788+
expect(
789+
agentBroadcastCalls(broadcast).map(([, payload]) => ({
790+
seq: (payload as { seq?: number }).seq,
791+
text: (payload as { data?: { text?: string } }).data?.text,
792+
delta: (payload as { data?: { delta?: string } }).data?.delta,
793+
})),
794+
).toEqual([
795+
{ seq: 1, text: "Hello", delta: "Hello" },
796+
{ seq: 2, text: "Hello world", delta: " world" },
797+
]);
798+
expect(vi.getTimerCount()).toBe(0);
799+
nowSpy.mockRestore();
800+
});
801+
755802
it("flushes coalesced assistant agent text before lifecycle end", () => {
756803
let now = 20_000;
757804
const nowSpy = vi.spyOn(Date, "now").mockImplementation(() => now);
758805
const { broadcast, nodeSendToSession, chatRunState, handler } = createHarness();
759806
registerNamedChatRun(chatRunState, "agent-flush");
760807

761808
emitAgentEvent(handler, "run-agent-flush", "assistant", { text: "Hello", delta: "Hello" });
762-
now = 20_050;
809+
now = 20_020;
763810
emitAgentEvent(
764811
handler,
765812
"run-agent-flush",
766813
"assistant",
767814
{ text: "Hello world", delta: " world" },
768815
{ seq: 2 },
769816
);
770-
now = 20_090;
817+
now = 20_040;
771818
emitAgentEvent(
772819
handler,
773820
"run-agent-flush",
@@ -957,14 +1004,14 @@ describe("agent event handler", () => {
9571004
nowSpy.mockRestore();
9581005
});
9591006

960-
it("coalesces thinking agent events under the chat delta throttle", () => {
1007+
it("coalesces thinking agent events inside one live-text pacing window", () => {
9611008
let now = 27_000;
9621009
const nowSpy = vi.spyOn(Date, "now").mockImplementation(() => now);
9631010
const { broadcast, nodeSendToSession, chatRunState, handler } = createHarness();
9641011
registerNamedChatRun(chatRunState, "agent-thinking");
9651012

9661013
for (let i = 0; i < 5; i += 1) {
967-
now = 27_000 + i * 20;
1014+
now = 27_000 + i * 10;
9681015
emitAgentEvent(
9691016
handler,
9701017
"run-agent-thinking",
@@ -1459,8 +1506,12 @@ describe("agent event handler", () => {
14591506
emitAgentEvent(handler, "run-trailing", "assistant", { text: "Hello world" });
14601507

14611508
expect(chatDeltaTexts(broadcast)).toEqual(["Hello"]);
1462-
now = 12_150;
1463-
vi.advanceTimersByTime(130);
1509+
now = 12_074;
1510+
vi.advanceTimersByTime(54);
1511+
expect(chatDeltaTexts(broadcast)).toEqual(["Hello"]);
1512+
1513+
now = 12_075;
1514+
vi.advanceTimersByTime(1);
14641515

14651516
expect(chatDeltaTexts(broadcast)).toEqual(["Hello", " world"]);
14661517
expect(vi.getTimerCount()).toBe(0);
@@ -1474,12 +1525,21 @@ describe("agent event handler", () => {
14741525
const { broadcast, chatRunState, handler } = createHarness();
14751526
registerNamedChatRun(chatRunState, "terminal-trailing");
14761527

1477-
emitAgentEvent(handler, "run-terminal-trailing", "assistant", { text: "Hello" });
1528+
emitAgentEvent(handler, "run-terminal-trailing", "assistant", {
1529+
text: "Hello",
1530+
delta: "Hello",
1531+
});
14781532
now = 13_020;
1479-
emitAgentEvent(handler, "run-terminal-trailing", "assistant", { text: "Hello world" });
1480-
expect(vi.getTimerCount()).toBe(1);
1533+
emitAgentEvent(
1534+
handler,
1535+
"run-terminal-trailing",
1536+
"assistant",
1537+
{ text: "Hello world", delta: " world" },
1538+
{ seq: 2 },
1539+
);
1540+
expect(vi.getTimerCount()).toBe(2);
14811541

1482-
emitLifecycleEnd(handler, "run-terminal-trailing");
1542+
emitLifecycleEnd(handler, "run-terminal-trailing", 3);
14831543
expect(vi.getTimerCount()).toBe(0);
14841544
const statesAtTerminal = chatBroadcastCalls(broadcast).map(
14851545
([, payload]) => (payload as { state?: string }).state,
@@ -1491,6 +1551,7 @@ describe("agent event handler", () => {
14911551
expect(
14921552
chatBroadcastCalls(broadcast).map(([, payload]) => (payload as { state?: string }).state),
14931553
).toEqual(statesAtTerminal);
1554+
expect(agentBroadcastCalls(broadcast)).toHaveLength(3);
14941555
nowSpy.mockRestore();
14951556
});
14961557

@@ -1501,16 +1562,26 @@ describe("agent event handler", () => {
15011562
const { broadcast, chatRunState, handler } = createHarness();
15021563
registerNamedChatRun(chatRunState, "shutdown-trailing");
15031564

1504-
emitAgentEvent(handler, "run-shutdown-trailing", "assistant", { text: "Hello" });
1565+
emitAgentEvent(handler, "run-shutdown-trailing", "assistant", {
1566+
text: "Hello",
1567+
delta: "Hello",
1568+
});
15051569
now = 14_020;
1506-
emitAgentEvent(handler, "run-shutdown-trailing", "assistant", { text: "Hello world" });
1507-
expect(vi.getTimerCount()).toBe(1);
1570+
emitAgentEvent(
1571+
handler,
1572+
"run-shutdown-trailing",
1573+
"assistant",
1574+
{ text: "Hello world", delta: " world" },
1575+
{ seq: 2 },
1576+
);
1577+
expect(vi.getTimerCount()).toBe(2);
15081578

15091579
chatRunState.clear();
15101580
expect(vi.getTimerCount()).toBe(0);
15111581
now = 14_500;
15121582
vi.advanceTimersByTime(1_000);
15131583
expect(chatDeltaTexts(broadcast)).toEqual(["Hello"]);
1584+
expect(agentBroadcastCalls(broadcast)).toHaveLength(1);
15141585
nowSpy.mockRestore();
15151586
});
15161587

0 commit comments

Comments
 (0)