diff --git a/ui/src/chat/state.ts b/ui/src/chat/state.ts index c42d7e2db..378659061 100644 --- a/ui/src/chat/state.ts +++ b/ui/src/chat/state.ts @@ -222,6 +222,10 @@ export function escapeOwnedByLayer(): boolean { let activeController: AbortController | null = null; +// Bumped on every conversation switch: a turn started in an earlier +// conversation is detached and must not write into the one now open. +let sessionEpoch = 0; + // The send path holds a stream loop that outlives the click that started it; a // module-level controller is what a Stop, or an unmount, aborts. function abortActiveTurn(): void { @@ -253,6 +257,10 @@ export async function refreshSessions(): Promise { export async function selectSession(id: string): Promise { if (!id) return; + // Switching conversation detaches the running turn: abort its stream and + // bump the epoch so its late writes land nowhere. + sessionEpoch++; + abortActiveTurn(); currentSession.value = id; messages.value = []; streamingTurn.value = null; @@ -264,7 +272,8 @@ export async function selectSession(id: string): Promise { // Resuming is the server's own command, so the transcript read below is of // a conversation the server considers current rather than a stale one. await api.chatMessage(channelID(), `/resume ${id}`); - messages.value = await readTranscript(id); + const transcript = await readTranscript(id); + if (isCurrentSession(id)) messages.value = transcript; } catch (err) { if (isCurrentSession(id)) sessionError.value = @@ -446,6 +455,9 @@ function currentPage(): string { } export async function sendMessage(retryOpts?: RetryOptions): Promise { + // The conversation this turn belongs to; a switch bumps sessionEpoch and + // detaches the turn, so its writes stop landing. + const epoch = sessionEpoch; const explicitText = retryOpts?.textOverride; const rawValue = explicitText !== undefined ? explicitText : composerText.value; @@ -508,16 +520,19 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise { let streamedText = ""; let finished = false; let timedOut = false; + let detached = false; let timeoutId: ReturnType | undefined; + let controller: AbortController | null = null; try { - const controller = new AbortController(); - activeController = controller; + const ctrl = new AbortController(); + controller = ctrl; + activeController = ctrl; const arm = () => { clearTimeout(timeoutId); timeoutId = setTimeout(() => { timedOut = true; - controller.abort(); + ctrl.abort(); }, STREAM_TIMEOUT_MS); }; arm(); @@ -533,7 +548,7 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise { page: currentPage(), voice: turn.voice, }, - { signal: controller.signal }, + { signal: ctrl.signal }, ); const body = response.body; if (!body) throw new Error("the chat stream returned no body"); @@ -548,6 +563,13 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise { // stream nobody collects. for (;;) { const { value, done } = await reader.read(); + if (epoch !== sessionEpoch) { + // Detached by a conversation switch mid-turn: stop reading and write + // nothing into the conversation now open. + detached = true; + await reader.cancel().catch(() => {}); + return; + } buffer += decoder.decode(value || new Uint8Array(), { stream: !done }); const frames = buffer.split("\n\n"); buffer = frames.pop() || ""; @@ -590,16 +612,18 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise { if (!finished) throw new Error("chat stream ended before completion"); - // /new opens an empty conversation, so the window clears instead of - // carrying the old one with a confirmation under it. - messages.value = - !isRetry && text.trim() === "/new" - ? [] - : [ - ...messages.value, - { from: "assistant", text: streamedText, tool_calls: activeTools }, - ]; - streamingTurn.value = null; + if (epoch === sessionEpoch) { + // /new opens an empty conversation, so the window clears instead of + // carrying the old one with a confirmation under it. + messages.value = + !isRetry && text.trim() === "/new" + ? [] + : [ + ...messages.value, + { from: "assistant", text: streamedText, tool_calls: activeTools }, + ]; + streamingTurn.value = null; + } statusText.value = "Ready"; // The turn succeeded; a failed session-list refresh is reported on its // own and must not turn into a "retry this turn" error. @@ -607,6 +631,11 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise { sessionError.value = `Could not refresh the session list: ${(err as Error).message || err}`; }); } catch (err) { + // A detached turn (conversation switched mid-turn) writes nothing. + if (epoch !== sessionEpoch) { + detached = true; + return; + } const failed = err as Error; // What already streamed is kept; the stop or failure note follows it. if (streamedText) { @@ -638,8 +667,14 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise { } finally { clearTimeout(timeoutId); rearmTimeout = null; - activeController = null; - isSending.value = false; + // Only the turn that still owns the controller clears the sending flag: a + // detached turn must not unlock the composer for a turn already running in + // the conversation now open. + if (controller && activeController === controller) { + activeController = null; + isSending.value = false; + if (detached) statusText.value = "Ready"; + } turnHooks.after?.(); } }