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;
// 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<void> {
export async function selectSession(id: string): Promise<void> {
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<void> {
// 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<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 rawValue =
explicitText !== undefined ? explicitText : composerText.value;
@@ -508,16 +520,19 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
let streamedText = "";
let finished = false;
let timedOut = false;
let detached = false;
let timeoutId: ReturnType<typeof setTimeout> | 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<void> {
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<void> {
// 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<void> {
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<void> {
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<void> {
} 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?.();
}
}