fix(ui): switching conversation detaches the running turn (#1729)
Quality / check (push) Canceled after 23s
deploy / gate (push) Successful in 4m47s
deploy / archied-image (push) Successful in 3m24s
deploy / agent-image (push) Successful in 11s
deploy / dist-zip (push) Skipped

selectSession now bumps a session epoch and aborts the in-flight stream
before switching, and the transcript read is applied only if the session is
still current. sendMessage captures the epoch at turn start: a detached turn
stops reading, cancels the reader, and writes no messages, streamingTurn or
session id; only the turn still owning the abort controller clears isSending,
so it cannot unlock the composer for a turn running in the new conversation.
This commit is contained in:
sam committed 2026-11-07 01:20:49 +11:00
1 parent a2c6341544
commit bd1acdd0cc
1 file changed
+52 -17
+52 -17
View File
@@ -222,6 +222,10 @@ export function escapeOwnedByLayer(): boolean {
let activeController: AbortController | null = null; 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 // 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. // module-level controller is what a Stop, or an unmount, aborts.
function abortActiveTurn(): void { function abortActiveTurn(): void {
@@ -253,6 +257,10 @@ export async function refreshSessions(): Promise<void> {
export async function selectSession(id: string): Promise<void> { export async function selectSession(id: string): Promise<void> {
if (!id) return; 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; currentSession.value = id;
messages.value = []; messages.value = [];
streamingTurn.value = null; streamingTurn.value = null;
@@ -264,7 +272,8 @@ export async function selectSession(id: string): Promise<void> {
// Resuming is the server's own command, so the transcript read below is of // 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. // a conversation the server considers current rather than a stale one.
await api.chatMessage(channelID(), `/resume ${id}`); await api.chatMessage(channelID(), `/resume ${id}`);
messages.value = await readTranscript(id); const transcript = await readTranscript(id);
if (isCurrentSession(id)) messages.value = transcript;
} catch (err) { } catch (err) {
if (isCurrentSession(id)) if (isCurrentSession(id))
sessionError.value = sessionError.value =
@@ -446,6 +455,9 @@ function currentPage(): string {
} }
export async function sendMessage(retryOpts?: RetryOptions): Promise<void> { export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
// 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 explicitText = retryOpts?.textOverride;
const rawValue = const rawValue =
explicitText !== undefined ? explicitText : composerText.value; explicitText !== undefined ? explicitText : composerText.value;
@@ -508,16 +520,19 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
let streamedText = ""; let streamedText = "";
let finished = false; let finished = false;
let timedOut = false; let timedOut = false;
let detached = false;
let timeoutId: ReturnType<typeof setTimeout> | undefined; let timeoutId: ReturnType<typeof setTimeout> | undefined;
let controller: AbortController | null = null;
try { try {
const controller = new AbortController(); const ctrl = new AbortController();
activeController = controller; controller = ctrl;
activeController = ctrl;
const arm = () => { const arm = () => {
clearTimeout(timeoutId); clearTimeout(timeoutId);
timeoutId = setTimeout(() => { timeoutId = setTimeout(() => {
timedOut = true; timedOut = true;
controller.abort(); ctrl.abort();
}, STREAM_TIMEOUT_MS); }, STREAM_TIMEOUT_MS);
}; };
arm(); arm();
@@ -533,7 +548,7 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
page: currentPage(), page: currentPage(),
voice: turn.voice, voice: turn.voice,
}, },
{ signal: controller.signal }, { signal: ctrl.signal },
); );
const body = response.body; const body = response.body;
if (!body) throw new Error("the chat stream returned no body"); if (!body) throw new Error("the chat stream returned no body");
@@ -548,6 +563,13 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
// stream nobody collects. // stream nobody collects.
for (;;) { for (;;) {
const { value, done } = await reader.read(); 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 }); buffer += decoder.decode(value || new Uint8Array(), { stream: !done });
const frames = buffer.split("\n\n"); const frames = buffer.split("\n\n");
buffer = frames.pop() || ""; buffer = frames.pop() || "";
@@ -590,16 +612,18 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
if (!finished) throw new Error("chat stream ended before completion"); if (!finished) throw new Error("chat stream ended before completion");
// /new opens an empty conversation, so the window clears instead of if (epoch === sessionEpoch) {
// carrying the old one with a confirmation under it. // /new opens an empty conversation, so the window clears instead of
messages.value = // carrying the old one with a confirmation under it.
!isRetry && text.trim() === "/new" messages.value =
? [] !isRetry && text.trim() === "/new"
: [ ? []
...messages.value, : [
{ from: "assistant", text: streamedText, tool_calls: activeTools }, ...messages.value,
]; { from: "assistant", text: streamedText, tool_calls: activeTools },
streamingTurn.value = null; ];
streamingTurn.value = null;
}
statusText.value = "Ready"; statusText.value = "Ready";
// The turn succeeded; a failed session-list refresh is reported on its // The turn succeeded; a failed session-list refresh is reported on its
// own and must not turn into a "retry this turn" error. // own and must not turn into a "retry this turn" error.
@@ -607,6 +631,11 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
sessionError.value = `Could not refresh the session list: ${(err as Error).message || err}`; sessionError.value = `Could not refresh the session list: ${(err as Error).message || err}`;
}); });
} catch (err) { } catch (err) {
// A detached turn (conversation switched mid-turn) writes nothing.
if (epoch !== sessionEpoch) {
detached = true;
return;
}
const failed = err as Error; const failed = err as Error;
// What already streamed is kept; the stop or failure note follows it. // What already streamed is kept; the stop or failure note follows it.
if (streamedText) { if (streamedText) {
@@ -638,8 +667,14 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
} finally { } finally {
clearTimeout(timeoutId); clearTimeout(timeoutId);
rearmTimeout = null; rearmTimeout = null;
activeController = null; // Only the turn that still owns the controller clears the sending flag: a
isSending.value = false; // 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?.(); turnHooks.after?.();
} }
} }