Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🧾 feat: Keep Every Lost Start Owed Until an Answer Resolves That Start (#17593)

Marco Beretta181137d117b2
diff --git a/packages/chat/src/core/__tests__/generations.spec.ts b/packages/chat/src/core/__tests__/generations.spec.ts
index f060838cbd..f024e4cfd5 100644
--- a/packages/chat/src/core/__tests__/generations.spec.ts
+++ b/packages/chat/src/core/__tests__/generations.spec.ts
@@ -3107,6 +3107,27 @@ describe('Chat lost starts across conversations and turns a retirement starts',
await queued;
expect(h.finishes).toHaveLength(1);
});
+
+ it.each([
+ ['under `new`, which a retry in another conversation does not resolve', 'new', 'unaddressable'],
+ ['in a known conversation, which a retry the server takes there resolves', 'convo-1', 'idle'],
+ ])('a lost start %s', async (_label, id, after) => {
+ const h = createHarness({ id });
+ h.transport.sendMessages.mockRejectedValueOnce(networkError());
+ await h.chat.sendMessage({ parts: [{ type: 'text', text: 'Hi' }] });
+ const retry = createStream({ streamId: 'convo-9', generationCreatedAt: 200 });
+ h.transport.sendMessages.mockResolvedValueOnce({ status: 'stream', stream: retry });
+ const sent = h.chat.sendMessage({ parts: [{ type: 'text', text: 'Again' }] });
+ await flush();
+ retry.push({
+ type: 'sync',
+ data: { conversationId: 'convo-9', responseMessage: placeholder },
+ } as ChatEvent);
+ retry.push(finalEvent());
+ await sent;
+
+ expect((await h.chat.stop()).status).toBe(after);
+ });
});
/** Table 1: every pause transition, the pause it leaves held, and the decisions it keeps. */
@@ -3382,6 +3403,124 @@ describe('Chat lost-start resolution', () => {
expect((await h.chat.stop()).status).toBe(expected);
});
+
+ it('after the second of two starts under `new` answers late, the first is still owed', async () => {
+ const h = createHarness({ id: 'new' });
+ const answers: Array<(result: ChatSendResult) => void> = [];
+ h.transport.sendMessages.mockImplementation(
+ () =>
+ new Promise<ChatSendResult>((resolve) => {
+ answers.push(resolve);
+ }),
+ );
+ for (const text of ['Hi', 'Again']) {
+ const sent = h.chat.sendMessage({ parts: [{ type: 'text', text }] });
+ await flush();
+ expect((await h.chat.stop()).status).toBe('unaddressable');
+ await sent;
+ }
+ answers[1]?.({ status: 'settled', conversationId: 'convo-8', generationProtocolVersion: 2 });
+ await flush();
+
+ expect(h.chat.status).toBe('error');
+ expect(h.chat.error).toBeDefined();
+ expect((await h.chat.stop()).status).toBe('unaddressable');
+ });
+
+ it('after a start answers settled just before its stop, nothing is owed', async () => {
+ const h = createHarness();
+ let answer: ((result: ChatSendResult) => void) | undefined;
+ h.transport.sendMessages.mockImplementationOnce(
+ () =>
+ new Promise<ChatSendResult>((resolve) => {
+ answer = resolve;
+ }),
+ );
+ const sent = h.chat.sendMessage({ parts: [{ type: 'text', text: 'Hi' }] });
+ await flush();
+ answer?.({ status: 'settled', conversationId: 'convo-1', generationProtocolVersion: 2 });
+ const stopped = await h.chat.stop();
+ await sent;
+ await flush();
+
+ expect(stopped.status).not.toBe('unaddressable');
+ expect(h.chat.status).toBe('ready');
+ expect((await h.chat.stop()).status).toBe('idle');
+ });
+
+ it('after a lost start under `new` answers late while its retry runs, the retry keeps its conversation', async () => {
+ const h = createHarness({ id: 'new' });
+ let answer: ((result: ChatSendResult) => void) | undefined;
+ h.transport.sendMessages.mockImplementationOnce(
+ () =>
+ new Promise<ChatSendResult>((resolve) => {
+ answer = resolve;
+ }),
+ );
+ const first = h.chat.sendMessage({ parts: [{ type: 'text', text: 'Hi' }] });
+ await flush();
+ expect((await h.chat.stop()).status).toBe('unaddressable');
+ await first;
+
+ const stream = createStream({ streamId: 'convo-2', generationCreatedAt: 200 });
+ h.transport.sendMessages.mockResolvedValueOnce({ status: 'stream', stream });
+ const retried = h.chat.sendMessage({ parts: [{ type: 'text', text: 'Again' }] });
+ await flush();
+ answer?.({ status: 'settled', conversationId: 'convo-1', generationProtocolVersion: 2 });
+ await flush();
+ stream.push({
+ type: 'sync',
+ data: { conversationId: 'convo-2', responseMessage: placeholder },
+ } as ChatEvent);
+ stream.push(finalEvent());
+ await retried;
+
+ expect(h.chat.conversationId).toBe('convo-2');
+ });
+
+ it('after a stop of a dropped first turn under `new` answers while its retry runs, the retry keeps its conversation', async () => {
+ const h = createHarness({ id: 'new' });
+ const dropped = createStream({ streamId: 'convo-1', generationCreatedAt: 100 });
+ h.transport.sendMessages.mockResolvedValueOnce({ status: 'stream', stream: dropped });
+ const first = h.chat.sendMessage({ parts: [{ type: 'text', text: 'Hi' }] });
+ await flush();
+ dropped.push(dropEvent);
+ await first;
+ await flush();
+
+ let answerStop: (() => void) | undefined;
+ h.transport.abort.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ answerStop = () => resolve({ success: true, aborted: 'convo-1' });
+ }),
+ );
+ const stopping = h.chat.stop();
+ await flush();
+ const stream = createStream({ streamId: 'convo-2', generationCreatedAt: 200 });
+ h.transport.sendMessages.mockResolvedValueOnce({ status: 'stream', stream });
+ const retried = h.chat.sendMessage({ parts: [{ type: 'text', text: 'Again' }] });
+ await flush();
+ answerStop?.();
+ await stopping;
+ await flush();
+ stream.push({
+ type: 'sync',
+ data: { conversationId: 'convo-2', responseMessage: placeholder },
+ } as ChatEvent);
+ stream.push(finalEvent());
+ await retried;
+
+ expect(h.chat.conversationId).toBe('convo-2');
+ });
+
+ it('after the cancelled start answers late that the server already finished it', async () => {
+ const h = createHarness();
+ await states.starting(h);
+ await events.lateSettled(h);
+
+ expect(h.after).toBe('idle');
+ });
});
/**
diff --git a/packages/chat/src/core/chat.ts b/packages/chat/src/core/chat.ts
index 758148fd0c..230dcc7d03 100644
--- a/packages/chat/src/core/chat.ts
+++ b/packages/chat/src/core/chat.ts
@@ -857,10 +857,10 @@ export class Chat {
/** The newest start handed to the transport, whose conversation a late answer must not replace. */
private latestStart?: ActiveRequest;
/**
- * A start that reached the transport and lost its response, with nothing to address it by. It
- * stays the caller's to stop until an answer resolves that start, or one its conversation covers.
+ * Starts that reached the transport and lost their response, with nothing to address them by,
+ * oldest first. Each stays the caller's to stop until an answer resolves that start itself.
*/
- private lostStart?: ActiveRequest;
+ private readonly lostStarts = new Set<ActiveRequest>();
/**
* The conversation this chat runs under: its id, until the server names the one it created for
* a chat started under `new`. Every later start, stop and reattachment addresses that one.
@@ -1176,7 +1176,7 @@ export class Chat {
if (!active && this.detached) {
return this.orUnaddressed(await this.stopDetached(this.detached));
}
- if (!active && this.lostStart) {
+ if (!active && this.unaddressed) {
/** A restored pause is stopped too, and the lost start is still the caller's. */
return this.action ? this.orUnaddressed(await this.stopPaused()) : unaddressable;
}
@@ -1231,7 +1231,7 @@ export class Chat {
*/
private orUnaddressed(result: ChatStopResult): ChatStopResult {
/** Only an answer about the lost start clears it, not a turn a callback started meanwhile. */
- return this.lostStart ? unaddressable : result;
+ return this.unaddressed ? unaddressable : result;
}
/** Sends a stop and records its answer on the generation, where every attachment reads it. */
@@ -1407,21 +1407,41 @@ export class Chat {
);
}
+ /** The newest start still lost, other than `except`, whose failure the chat keeps reporting. */
+ private newestLostStart(except?: ActiveRequest): ActiveRequest | undefined {
+ let newest: ActiveRequest | undefined;
+ for (const lost of this.lostStarts) {
+ if (lost !== except) {
+ newest = lost;
+ }
+ }
+ return newest;
+ }
+
+ /** Whether any start is still lost, which only the host's own abort can reach. */
+ private get unaddressed(): boolean {
+ return this.lostStarts.size > 0;
+ }
+
/**
- * A start the chat reported lost is now answered for: its marker clears, and the failure it
- * reported resolves unless a newer turn owns the chat.
+ * A start the chat reported lost is now answered for: its marker clears, a newer lost start keeps
+ * its own, and the failure it reported gives way to the newest start still lost, or resolves,
+ * unless a newer turn owns the chat.
*/
private resolveLostStart(active: ActiveRequest): void {
active.resolved = true;
- if (this.lostStart !== active) {
- return;
- }
- this.lostStart = undefined;
+ this.lostStarts.delete(active);
const failed = active.disconnected;
if (this.disposed || this.active || !failed || this.error !== failed) {
return;
}
- this.clearFailure();
+ const owed = this.newestLostStart()?.disconnected;
+ if (!owed) {
+ this.clearFailure();
+ this.notify();
+ return;
+ }
+ this.init.state.error = owed;
this.notify();
}
@@ -1432,11 +1452,14 @@ export class Chat {
* Returns whether it released one.
*/
private releaseLostStart(): boolean {
- if (!this.lostStart || this.lostStart.sentUnder === Constants.NEW_CONVO) {
- return false;
+ let released = false;
+ for (const lost of this.lostStarts) {
+ if (lost.sentUnder !== Constants.NEW_CONVO) {
+ this.lostStarts.delete(lost);
+ released = true;
+ }
}
- this.lostStart = undefined;
- return true;
+ return released;
}
/**
@@ -1446,7 +1469,7 @@ export class Chat {
private startsAfter(since: ActiveRequest | undefined): boolean {
const latest = this.latestStart;
return (
- latest != null && latest !== since && (latest === this.active || latest === this.lostStart)
+ latest != null && latest !== since && (latest === this.active || this.lostStarts.has(latest))
);
}
@@ -1592,7 +1615,7 @@ export class Chat {
const { conversationId } = generation;
const named = conversationId !== Constants.NEW_CONVO ? conversationId : undefined;
/** A lost start still owed its own abort keeps the failure it reported. */
- const owed = this.lostStart && this.error ? this.error : undefined;
+ const owed = this.unaddressed && this.error ? this.error : undefined;
this.publish(
{ ...outcome, conversationId: named },
generation.responseId,
@@ -1646,7 +1669,7 @@ export class Chat {
if (this.publishUnframedStop(result, unframed)) {
return getStopResult(result, generation.stoppedConversationId);
}
- if (this.status === 'error' && !this.lostStart) {
+ if (this.status === 'error' && !this.unaddressed) {
/**
* The stop confirmed the end a dropped connection left unknown. A lost start still owed its
* own abort keeps the failure it reported.
@@ -2388,7 +2411,7 @@ export class Chat {
};
} else if (active.sent && !active.stream && !active.reattach && !active.resolved) {
/** The start may have reached the server, which answered nothing this chat can address. */
- this.lostStart = active;
+ this.lostStarts.add(active);
}
}
/**
@@ -2416,7 +2439,7 @@ export class Chat {
const { responseId, responseUnknown, responseless, conversationId } = active.generation;
const named = conversationId !== Constants.NEW_CONVO ? conversationId : undefined;
/** A lost start still owed its own abort keeps the failure it reported. */
- const owed = this.lostStart !== active ? this.lostStart?.disconnected : undefined;
+ const owed = this.newestLostStart(active)?.disconnected;
this.publish(
{ ...outcome, conversationId: named },
responseId,