From 3807c247e9800fba11a0d55c566bf99a37b7fd23 Mon Sep 17 00:00:00 2001 From: Tamaz_Sujashvili Date: Wed, 10 Jun 2026 03:09:44 +0400 Subject: [PATCH] Fix false streaming and live UI reset when switching sessions. Clear stale busy/stream state before async message loads and restore snapshotted turn HTML when returning to an active stream. Co-authored-by: Cursor --- CHANGELOG.md | 5 ++ static/sessions.js | 46 ++++++++++++--- tests/test_session_switch_busy_race.py | 79 ++++++++++++++++++++++++++ 3 files changed, 121 insertions(+), 9 deletions(-) create mode 100644 tests/test_session_switch_busy_race.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 8df5ac274..ed4f59f49 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,11 @@ ## [Unreleased] +### Fixed + +- **Session falsely streams after sidebar switch:** `loadSession` now clears `S.busy` and `S.activeStreamId` as soon as session metadata confirms there is no `active_stream_id`, before the async message-load gap. Prevents the previous session's busy flag from making an idle chat show Stop/spinner/thinking. +- **Activity timer resets when switching back to a streaming chat:** `loadSession` snapshots the live turn DOM before replacing `msgInner`, ensures an `INFLIGHT` bucket exists for the snapshot, and restores that HTML on the `active_stream_id` return path instead of always rebuilding the worklog shell from scratch. + ## [v0.51.346] — 2026-06-09 — Release LJ (PWA notification controls) ### Added diff --git a/static/sessions.js b/static/sessions.js index 36409307c..d85bf1dc3 100644 --- a/static/sessions.js +++ b/static/sessions.js @@ -794,6 +794,22 @@ async function loadSession(sid){ // close streams for the session the user actually landed on (#1060 guard, // extended to cover the new pre-switch await). if (_loadingSessionId !== sid) return; + // Snapshot the live turn before msgInner is replaced. Preserves the activity + // timer, partial response, and tool cards so switching back does not rebuild + // the stream UI from scratch. + if( + (S.busy||S.activeStreamId||(INFLIGHT&&INFLIGHT[currentSid]))&& + typeof snapshotLiveTurnHtmlForSession==='function' + ){ + if(!INFLIGHT[currentSid]){ + INFLIGHT[currentSid]={ + messages:Array.isArray(S.messages)?[...S.messages]:[], + uploaded:[], + toolCalls:Array.isArray(S.toolCalls)?[...S.toolCalls]:[], + }; + } + snapshotLiveTurnHtmlForSession(currentSid); + } } if (currentSid !== sid || forceReload) { // #3306: When force-reloading the currently-active session (e.g. external @@ -935,14 +951,21 @@ async function loadSession(sid){ if(typeof startSessionStream==='function') startSessionStream(S.session.session_id); const activeStreamId=S.session.active_stream_id||null; - // If the server says the session is idle, discard any browser-side inflight - // cache left behind by a crashed/restarted stream. Otherwise the UI can keep - // showing a permanent thinking/running state even though active_streams=0. - if(!activeStreamId&&INFLIGHT[sid]){ - delete INFLIGHT[sid]; - if(typeof clearInflightState==='function') clearInflightState(sid); + // If the server says the session is idle, reset browser-side streaming flags + // NOW — before the async _ensureMessagesLoaded gap below. Without this, + // S.busy can remain true from a still-running stream in the PREVIOUS session + // while S.session.session_id has already advanced to the new one. + // _isSessionLocallyStreaming() checks (isActive && S.busy), so during the + // async window the new session would appear locally-streaming (sidebar spinner, + // Stop button, thinking state on an idle chat). Also clears stale INFLIGHT + // entries left behind by a crashed/restarted stream. + if(!activeStreamId){ S.activeStreamId=null; S.busy=false; + if(INFLIGHT[sid]){ + delete INFLIGHT[sid]; + if(typeof clearInflightState==='function') clearInflightState(sid); + } } function _mergePendingSessionMessage(session,messages){ @@ -1155,10 +1178,15 @@ async function loadSession(sid){ updateSendBtn(); setStatus(''); setComposerStatus(''); - // syncTopbar();renderMessages();appendThinking();loadDir('.'); syncTopbar();renderMessages(sameSessionForceReload?{preserveScroll:true}:undefined); - if(typeof ensureLiveWorklogShell==='function') ensureLiveWorklogShell(); - else appendThinking(); + let restoredLiveTurn=false; + if(typeof restoreLiveTurnHtmlForSession==='function'){ + restoredLiveTurn=restoreLiveTurnHtmlForSession(sid); + } + if(!restoredLiveTurn){ + if(typeof ensureLiveWorklogShell==='function') ensureLiveWorklogShell(); + else appendThinking(); + } loadDir('.'); updateQueueBadge(sid); startApprovalPolling(sid); diff --git a/tests/test_session_switch_busy_race.py b/tests/test_session_switch_busy_race.py new file mode 100644 index 000000000..8ba18ec52 --- /dev/null +++ b/tests/test_session_switch_busy_race.py @@ -0,0 +1,79 @@ +"""Regression coverage for session-switch busy-state race and live-turn restore. + +Switching from a streaming session to an idle one must clear S.busy before the +async _ensureMessagesLoaded gap. Otherwise _isSessionLocallyStreaming() treats +the newly opened session as locally streaming while messages are still loading. + +Switching back to a streaming session must restore the snapshotted live turn +instead of rebuilding thinking/worklog chrome from scratch. +""" + +from pathlib import Path + +REPO = Path(__file__).resolve().parents[1] +SESSIONS_SRC = (REPO / "static" / "sessions.js").read_text(encoding="utf-8") +UI_SRC = (REPO / "static" / "ui.js").read_text(encoding="utf-8") + + +def _function_body(src: str, signature: str) -> str: + start = src.find(signature) + assert start != -1, f"missing {signature}" + brace = src.find("{", start) + assert brace != -1, f"missing opening brace for {signature}" + depth = 0 + for i in range(brace, len(src)): + ch = src[i] + if ch == "{": + depth += 1 + elif ch == "}": + depth -= 1 + if depth == 0: + return src[brace + 1 : i] + raise AssertionError(f"could not extract function body for {signature}") + + +def test_loadSession_clears_busy_before_async_message_load_when_server_idle(): + body = _function_body(SESSIONS_SRC, "async function loadSession(") + + idle_reset = body.find("if(!activeStreamId){") + assert idle_reset != -1, "loadSession must gate idle cleanup on missing active_stream_id" + idle_block = body[idle_reset : idle_reset + 500] + assert "S.busy=false" in idle_block, "idle switch must clear S.busy immediately" + assert "S.activeStreamId=null" in idle_block, "idle switch must clear S.activeStreamId immediately" + + ensure_load = body.find("await _ensureMessagesLoaded(sid)") + assert ensure_load != -1, "loadSession must still lazy-load messages for idle sessions" + assert idle_reset < ensure_load, ( + "S.busy must be cleared before _ensureMessagesLoaded so session-list polling " + "during the async gap does not mark the new session as locally streaming" + ) + + +def test_loadSession_snapshots_live_turn_before_wiping_message_pane(): + body = _function_body(SESSIONS_SRC, "async function loadSession(") + + snap_pos = body.find("snapshotLiveTurnHtmlForSession(currentSid)") + wipe_pos = body.find('_msgInner.innerHTML=\'