from unittest.mock import patch, MagicMock

def test_no_extraneous_pop_when_prior_session_renders():
 """Verifies that imscope push/pop balance is maintained when the
 prior-session render path executes. Calls render_prior_session_view
 (the narrow function) instead of render_main_interface (kitchen sink).
 """
 from src import gui_2
 app_instance = MagicMock()
 app_instance.is_viewing_prior_session = True
 app_instance.perf_profiling_enabled = False
 app_instance.prior_disc_entries = [
  {"role": "User", "content": "test", "collapsed": False, "ts": "t1"}
 ]

 push_count = {"n": 0}
 pop_count = {"n": 0}
 def _track_push(*a, **k): push_count["n"] += 1
 def _track_pop(*a, **k): pop_count["n"] += 1

 with patch("src.gui_2.imgui") as mock_imgui, \
   patch("src.gui_2.imscope") as mock_imscope, \
   patch("src.gui_2.theme") as mock_theme, \
   patch("src.gui_2.markdown_helper") as mock_md:

  mock_imscope.style_color.return_value.__enter__.side_effect = _track_push
  mock_imscope.style_color.return_value.__exit__.side_effect = lambda *a: (pop_count.__setitem__("n", pop_count["n"] + 1) or False)
  mock_imscope.child.return_value.__enter__ = MagicMock()
  mock_imscope.child.return_value.__exit__ = MagicMock(return_value=False)
  mock_imscope.id.return_value.__enter__ = MagicMock()
  mock_imscope.id.return_value.__exit__ = MagicMock(return_value=False)

  mock_imgui.Col_ = MagicMock()
  mock_imgui.button = MagicMock(return_value=False)
  mock_imgui.same_line = MagicMock()
  mock_imgui.text_colored = MagicMock()
  mock_imgui.separator = MagicMock()
  mock_imgui.get_content_region_avail = MagicMock(return_value=MagicMock(x=800.0, y=600.0))
  mock_imgui.ImVec2 = lambda *a: MagicMock(x=a[0], y=a[1])
  mock_imgui.WindowFlags_ = MagicMock()

  mock_theme.get_color = MagicMock(return_value=MagicMock())
  mock_theme.ai_text_style.return_value.__enter__ = MagicMock()
  mock_theme.ai_text_style.return_value.__exit__ = MagicMock(return_value=False)

  mock_md.render = MagicMock()

  gui_2.render_prior_session_view(app_instance)

 assert push_count["n"] == pop_count["n"], f"Push/pop imbalance: pushes={push_count['n']}, pops={pop_count['n']}"
