HERMES-GIELIE/tests/test_issue1690_scroll_completion.py

100 lines
5.3 KiB
Python
Raw Normal View History

from pathlib import Path
REPO = Path(__file__).resolve().parents[1]
UI_JS = (REPO / "static" / "ui.js").read_text(encoding="utf-8")
MESSAGES_JS = (REPO / "static" / "messages.js").read_text(encoding="utf-8")
SESSIONS_JS = (REPO / "static" / "sessions.js").read_text(encoding="utf-8")
def _function_body(src: str, name: str) -> str:
start = src.index(f"function {name}")
brace = src.index("{", start)
depth = 0
for i in range(brace, len(src)):
if src[i] == "{":
depth += 1
elif src[i] == "}":
depth -= 1
if depth == 0:
return src[start : i + 1]
raise AssertionError(f"function {name} body not found")
def _event_listener_body(src: str, event_name: str) -> str:
needle = f"source.addEventListener('{event_name}'"
start = src.index(needle)
brace = src.index("{", start)
depth = 0
for i in range(brace, len(src)):
if src[i] == "{":
depth += 1
elif src[i] == "}":
depth -= 1
if depth == 0:
return src[start : i + 1]
raise AssertionError(f"event listener {event_name!r} body not found")
def test_terminal_done_render_preserves_manual_scroll_after_active_stream_is_cleared():
done_block = _event_listener_body(MESSAGES_JS, "done")
clear_idx = done_block.index("S.activeStreamId=null")
render_idx = done_block.index("renderMessages({preserveScroll:true})")
assert clear_idx < render_idx, (
"the done handler should clear stream liveness before the final render, "
"but must pass preserveScroll so renderMessages does not infer bottom-pin "
"from S.activeStreamId alone"
)
def test_render_messages_preserve_scroll_option_uses_user_pin_state_not_stream_liveness():
render_body = _function_body(UI_JS, "renderMessages")
scroll_helper = _function_body(UI_JS, "_scrollAfterMessageRender")
[HELD — independent review pending] Release v0.51.294 — stage-3401 (live-to-final redesign #3401 + 4 deep-review fixes) (#3741) * Harden interrupted recovery control filtering * Redesign live-to-final assistant replies * Fix live activity anchor test fixture * Fix CI lint issues for live reply tests * Strengthen live progress prompt contract * Recover PR #3401 refresh on origin/master * Repair live-to-final refresh regressions * Fix live worklog refresh regressions * Show live footer timer on initial stream start * Restore live stream shell after reload * Preserve per-frame live SSE replay cursors * Preserve reasoning as Worklog Thinking cards * Quiet Worklog Thinking card styling * Align Worklog Thinking card styling * Scope live Worklog Thinking cards by segment * Suppress exact duplicate settled Thinking * Close #3401 merge review test gaps * fix(#3401): resolve 4 deep-review regressions (inline-think, reconnect-dup, neon skin, busy-gate worklog) Deep review (Codex diff-vs-master + live-browser drive) of the live-to-final refactor surfaced 4 regressions vs master that the rewritten suite no longer guarded: 1. Inline <think>…</think>answer reasoning vanished — _assistantReasoningPayloadText used $-anchored regexes so a leading think block + visible answer extracted nothing and the Thinking card never rendered. Removed the 3 $ anchors to match the (non-anchored) display stripper. Live: inline-think thinking-only turn now renders. 2. (CORE) reconnect/reload duplicated the live reply — _rememberRunJournalCursor advanced a closure-local seq but never wrote INFLIGHT[activeSid].lastRunJournalSeq, so a reload replayed the journal from after_seq=0 over restored lastAssistantText. Now mirrors the cursor onto INFLIGHT + schedules a throttled persist. 3. Neon skin silently broke — PR deleted the :root[data-skin="neon"] CSS but left Neon in the picker. Restored the neon CSS block from master. 4. Settled tool-worklog rebuild gated purely on !S.busy — dropped every prior settled turn's worklog when renderMessages re-ran during an active stream (switch-back to an in-progress session). Restored master's !S.busy || (S.toolCalls && S.toolCalls.length). Live: busy re-render now preserves tool cards (4→4, was 4→0). Live-verified all 4 + confirmed #3709/#3592 invariants still hold (1 thinking card, none below footer; distinct siblings preserved). + tests/test_issue3401_deep_review_fixes.py (7). * test(#3401): realign 3 stale source-shape assertions to the deep-review fixes Fix commit changed two source literals that existing stage tests scanned for: - test_live_activity_timeline.py (x2): split anchor 'if(!S.busy){' → the restored 'if(!S.busy || (S.toolCalls&&S.toolCalls.length)){' guard (fix 4). - test_run_journal_frontend_static.py: 'after_seq=0' not in source — fix 2's comment contained that literal; rephrased the comment to 'the zero floor (after_seq of 0)'. Intent of all three assertions unchanged; only the matched string updated. No code behavior change. * docs(changelog): v0.51.294 — Release JJ (stage-3401, #3401 live-to-final redesign) --------- Co-authored-by: Frank Song <franksong2702@gmail.com> Co-authored-by: Nathan-Hermes <nesquena-hermes@users.noreply.github.com> Co-authored-by: nesquena-hermes <[email protected]>
2026-06-06 19:12:37 +00:00
follow_helper = _function_body(UI_JS, "_followMessagesAfterDomReplace")
assert "function renderMessages(options)" in render_body
assert "const preserveScroll=!!(options&&options.preserveScroll);" in render_body
assert "_scrollAfterMessageRender(preserveScroll, scrollSnapshot);" in render_body
assert "const scrollSnapshot=(preserveScroll||_messageUserUnpinned)?_captureMessageScrollSnapshot():null" in render_body
assert "if(preserveScroll){" in scroll_helper
# #4124: a reader clearly away from the bottom (>250px) is treated as an active
# reading position, so the forced follow-to-bottom is gated behind it.
assert "const readerAwayFromBottom=" in scroll_helper
assert "Number(scrollSnapshot.bottom)>250" in scroll_helper
assert "// Keep master's follow heuristic" in scroll_helper
assert "if(!readerAwayFromBottom && !_messageUserUnpinned && _followMessagesAfterDomReplace()) return;\n _restoreMessageScrollSnapshot(scrollSnapshot);\n _maybeShowNewMessageScrollCue(scrollSnapshot);\n return;\n }" in scroll_helper
[HELD — independent review pending] Release v0.51.294 — stage-3401 (live-to-final redesign #3401 + 4 deep-review fixes) (#3741) * Harden interrupted recovery control filtering * Redesign live-to-final assistant replies * Fix live activity anchor test fixture * Fix CI lint issues for live reply tests * Strengthen live progress prompt contract * Recover PR #3401 refresh on origin/master * Repair live-to-final refresh regressions * Fix live worklog refresh regressions * Show live footer timer on initial stream start * Restore live stream shell after reload * Preserve per-frame live SSE replay cursors * Preserve reasoning as Worklog Thinking cards * Quiet Worklog Thinking card styling * Align Worklog Thinking card styling * Scope live Worklog Thinking cards by segment * Suppress exact duplicate settled Thinking * Close #3401 merge review test gaps * fix(#3401): resolve 4 deep-review regressions (inline-think, reconnect-dup, neon skin, busy-gate worklog) Deep review (Codex diff-vs-master + live-browser drive) of the live-to-final refactor surfaced 4 regressions vs master that the rewritten suite no longer guarded: 1. Inline <think>…</think>answer reasoning vanished — _assistantReasoningPayloadText used $-anchored regexes so a leading think block + visible answer extracted nothing and the Thinking card never rendered. Removed the 3 $ anchors to match the (non-anchored) display stripper. Live: inline-think thinking-only turn now renders. 2. (CORE) reconnect/reload duplicated the live reply — _rememberRunJournalCursor advanced a closure-local seq but never wrote INFLIGHT[activeSid].lastRunJournalSeq, so a reload replayed the journal from after_seq=0 over restored lastAssistantText. Now mirrors the cursor onto INFLIGHT + schedules a throttled persist. 3. Neon skin silently broke — PR deleted the :root[data-skin="neon"] CSS but left Neon in the picker. Restored the neon CSS block from master. 4. Settled tool-worklog rebuild gated purely on !S.busy — dropped every prior settled turn's worklog when renderMessages re-ran during an active stream (switch-back to an in-progress session). Restored master's !S.busy || (S.toolCalls && S.toolCalls.length). Live: busy re-render now preserves tool cards (4→4, was 4→0). Live-verified all 4 + confirmed #3709/#3592 invariants still hold (1 thinking card, none below footer; distinct siblings preserved). + tests/test_issue3401_deep_review_fixes.py (7). * test(#3401): realign 3 stale source-shape assertions to the deep-review fixes Fix commit changed two source literals that existing stage tests scanned for: - test_live_activity_timeline.py (x2): split anchor 'if(!S.busy){' → the restored 'if(!S.busy || (S.toolCalls&&S.toolCalls.length)){' guard (fix 4). - test_run_journal_frontend_static.py: 'after_seq=0' not in source — fix 2's comment contained that literal; rephrased the comment to 'the zero floor (after_seq of 0)'. Intent of all three assertions unchanged; only the matched string updated. No code behavior change. * docs(changelog): v0.51.294 — Release JJ (stage-3401, #3401 live-to-final redesign) --------- Co-authored-by: Frank Song <franksong2702@gmail.com> Co-authored-by: Nathan-Hermes <nesquena-hermes@users.noreply.github.com> Co-authored-by: nesquena-hermes <[email protected]>
2026-06-06 19:12:37 +00:00
assert "_shouldFollowMessagesOnDomReplace()" in follow_helper
assert "scrollToBottom();" in follow_helper
fix(webui): restore unpinned reader after mid-stream wipe-and-rebuild scroll clamp renderMessages() rebuilds the transcript via inner.innerHTML='' then re-appends rows. That wipe collapses #msgInner scrollHeight toward the empty-table height, so the browser is forced to clamp #messages.scrollTop down to the new near-zero max -- a browser primitive (no JS writes scrollTop; overflow-anchor does not govern it). When this rebuild happens mid-stream while a reader has scrolled up into history (_messageUserUnpinned), _scrollAfterMessageRender took the S.activeStreamId branch and called scrollIfPinned(), which is a no-op for an unpinned reader -- so the clamped-to-0 scrollTop was never restored and the reader was stranded at the top. Fix: in that branch, when the reader is unpinned and a pre-wipe scroll snapshot exists (renderMessages already captures one whenever _messageUserUnpinned), restore the snapshot instead of the no-op. Pinned / tail-following readers keep scrollIfPinned() so live-follow is unchanged. Reuses the existing _restoreMessageScrollSnapshot helper (same one the preserveScroll and idle-unpin branches use), so no new core-timing risk. Tests: test_wipe_rows0_streaming_unpinned_restore.py executes the real extracted _scrollAfterMessageRender against a fake #messages + instrumented restore stubs and asserts the unpinned+activeStreamId+snapshot case restores (scrollTop returns to the pre-clamp value) while pinned / no-snapshot cases fall back to scrollIfPinned(); mutation-checked (reverting to the bare scrollIfPinned() fails the behavioral asserts). Updates the test_issue1690 source-lock for the new branch structure.
2026-07-06 12:32:52 +00:00
# Mid-stream re-render branch (issue: wipe-rows0 scrollHeight-collapse jump-back).
# An unpinned reader (scrolled up into history) must have their pre-wipe viewport
# RESTORED — scrollIfPinned() is a no-op for the unpinned case and cannot undo the
# browser's scrollTop clamp from the inner.innerHTML='' wipe, so it stranded the
# reader at the top. Pinned/tail-following readers still take scrollIfPinned().
assert "if(S.activeStreamId){" in scroll_helper
assert "if(_messageUserUnpinned && scrollSnapshot){\n _restoreMessageScrollSnapshot(scrollSnapshot);\n _maybeShowNewMessageScrollCue(scrollSnapshot);\n return;\n }\n scrollIfPinned();\n return;\n }" in scroll_helper
def test_cached_render_path_uses_same_scroll_policy_as_fresh_render():
render_body = _function_body(UI_JS, "renderMessages")
cached_branch = render_body[render_body.index("if(sid&&sid!==_sessionHtmlCacheSid") : render_body.index("const compressionState=")]
assert "_scrollAfterMessageRender(preserveScroll, scrollSnapshot);" in cached_branch
assert "if(S.activeStreamId){scrollIfPinned();}else{scrollToBottom();}" not in cached_branch
def test_session_switch_and_idle_session_load_keep_default_bottom_pin_behavior():
load_session = _function_body(SESSIONS_JS, "loadSession")
idle_branch = load_session[load_session.index("}else{\n S.busy=false;") : load_session.index("// Sync context usage indicator")]
# #3326: the idle branch now renders with a CONDITIONAL preserveScroll —
# `renderMessages(sameSessionForceReload?{preserveScroll:true}:undefined)`.
# For a normal cross-session idle load (currentSid!==sid) sameSessionForceReload
# is false, so the arg is undefined and the default bottom-pin behavior (#1690)
# is unchanged. preserveScroll only applies to a same-session external
# force-refresh (#3239), which is a different code path from #1690's scenario.
assert "syncTopbar();renderMessages(sameSessionForceReload?{preserveScroll:true}:undefined);" in idle_branch
# The idle path must NOT unconditionally preserveScroll — it stays bottom-pinned
# for cross-session loads. Guard against a regression to an always-on preserve.
assert "renderMessages({preserveScroll:true})" not in idle_branch