Skip to content

The agent that turns websites into APIs!

fix(cursor): buffer streamed model text; flush as single blocks

Cursor Agent2f91e7c29e48
diff --git a/src/reverse_api/cursor_engineer.py b/src/reverse_api/cursor_engineer.py
index 482e6da..9b2ee5f 100644
--- a/src/reverse_api/cursor_engineer.py
+++ b/src/reverse_api/cursor_engineer.py
@@ -60,6 +60,8 @@ class CursorEngineer(BaseEngineer):
cm = cursor_model or model or "composer-2"
super().__init__(run_id=run_id, har_path=har_path, prompt=prompt, model=cm, **kwargs)
self.cursor_model = cm
+ self._cursor_thinking_acc = ""
+ self._cursor_assistant_acc = ""
def _workspace_cwd(self) -> str:
return str(self.scripts_dir.parent.parent)
@@ -71,20 +73,55 @@ class CursorEngineer(BaseEngineer):
if key in usage and isinstance(usage[key], (int, float)):
self.usage_metadata[key] = self.usage_metadata.get(key, 0) + int(usage[key])
+ def _cursor_reset_stream_buffers(self) -> None:
+ self._cursor_thinking_acc = ""
+ self._cursor_assistant_acc = ""
+
+ def _cursor_feed_thinking(self, fragment: str) -> None:
+ self._cursor_thinking_acc += fragment
+
+ def _cursor_feed_assistant(self, text: str) -> None:
+ """Merge assistant snapshots (Cursor often sends growing full-message text)."""
+ if not text:
+ return
+ old = self._cursor_assistant_acc
+ if not old.strip():
+ self._cursor_assistant_acc = text
+ return
+ if text.startswith(old):
+ self._cursor_assistant_acc = text
+ return
+ self._cursor_assistant_acc = old.rstrip() + "\n\n" + text.lstrip()
+
+ def _cursor_narrative_nonempty(self) -> bool:
+ return bool(self._cursor_thinking_acc.strip() or self._cursor_assistant_acc.strip())
+
+ def _cursor_flush_narrative(self) -> None:
+ """Emit accumulated model text as one UI block + one message_store entry."""
+ parts: list[str] = []
+ if self._cursor_thinking_acc.strip():
+ parts.append(self._cursor_thinking_acc.strip())
+ if self._cursor_assistant_acc.strip():
+ parts.append(self._cursor_assistant_acc.strip())
+ combined = "\n\n".join(parts)
+ if not combined:
+ return
+ self.ui.thinking_block(combined)
+ self.message_store.save_thinking(combined)
+ self._cursor_thinking_acc = ""
+ self._cursor_assistant_acc = ""
+
async def _dispatch_stream_event(self, event: dict[str, Any]) -> None:
et = event.get("type")
if et == "thinking" and event.get("text"):
- t = str(event["text"])
- self.ui.thinking(t)
- self.message_store.save_thinking(t)
+ self._cursor_feed_thinking(str(event["text"]))
elif et == "assistant" and event.get("text"):
- t = str(event["text"])
- self.ui.thinking(t)
- self.message_store.save_thinking(t)
+ self._cursor_feed_assistant(str(event["text"]))
elif et == "tool_call":
name = str(event.get("name") or "tool")
status = event.get("status")
if status == "running":
+ self._cursor_flush_narrative()
args = event.get("args") if isinstance(event.get("args"), dict) else {}
self.ui.tool_start(name, args)
self.message_store.save_tool_start(name, args)
@@ -123,6 +160,8 @@ class CursorEngineer(BaseEngineer):
if not node_exe:
return {"error": "node not found in PATH"}
+ self._cursor_reset_stream_buffers()
+
proc = await asyncio.create_subprocess_exec(
node_exe,
str(_BRIDGE_SCRIPT),
@@ -138,7 +177,6 @@ class CursorEngineer(BaseEngineer):
await proc.stdin.drain()
proc.stdin.close()
- assistant_chunks: list[str] = []
assert proc.stdout is not None
while True:
line_b = await proc.stdout.readline()
@@ -155,8 +193,6 @@ class CursorEngineer(BaseEngineer):
if t == "stream" and isinstance(obj.get("event"), dict):
ev = obj["event"]
await self._dispatch_stream_event(ev)
- if ev.get("type") == "assistant" and ev.get("text"):
- assistant_chunks.append(str(ev["text"]))
elif t == "agent":
pass
elif t == "done":
@@ -165,9 +201,11 @@ class CursorEngineer(BaseEngineer):
await proc.wait()
return {"error": str(run_result.get("result") or "run error")}
self._merge_usage_from_bridge(obj.get("usage"))
+ had_narrative = self._cursor_narrative_nonempty()
+ self._cursor_flush_narrative()
rr = run_result.get("result")
- if isinstance(rr, str) and rr.strip() and not assistant_chunks:
- self.ui.thinking(rr)
+ if isinstance(rr, str) and rr.strip() and not had_narrative:
+ self.ui.thinking_block(rr)
self.message_store.save_thinking(rr)
code = await proc.wait()
stderr_b = await proc.stderr.read() if proc.stderr else b""
diff --git a/src/reverse_api/tui.py b/src/reverse_api/tui.py
index 4ae362f..ea443ac 100644
--- a/src/reverse_api/tui.py
+++ b/src/reverse_api/tui.py
@@ -1,6 +1,7 @@
"""Rich Terminal UI for Claude SDK interactions."""
from rich.console import Console
+from rich.padding import Padding
from rich.text import Text
# Theme configuration
@@ -128,6 +129,23 @@ class ClaudeUI:
display_text = display_text[:max_length] + "..."
self.console.print(f" [dim].. {display_text}[/dim]")
+ def thinking_block(self, text: str, max_chars: int = 8000) -> None:
+ """Print one cohesive model reasoning / reply block (not token-by-token).
+
+ Used by the Cursor SDK path where the bridge streams fine-grained deltas;
+ the engineer buffers those and flushes them here as a single visual unit.
+ """
+ if not self.verbose:
+ return
+ raw = (text or "").strip()
+ if len(raw) < 2:
+ return
+ if len(raw) > max_chars:
+ raw = raw[:max_chars] + "\n…"
+ self.console.print()
+ self.console.print(Padding(Text(raw, style="dim"), (0, 0, 0, 2)))
+ self.console.print()
+
def progress(self, message: str) -> None:
"""Display a progress message."""
self.console.print(f" [dim italic]{message}[/dim italic]")
diff --git a/tests/test_cursor_engineer.py b/tests/test_cursor_engineer.py
index 95b2807..d73a707 100644
--- a/tests/test_cursor_engineer.py
+++ b/tests/test_cursor_engineer.py
@@ -81,3 +81,27 @@ def test_ensure_bridge_missing_script(tmp_path: Path, monkeypatch: pytest.Monkey
monkeypatch.setattr(ce, "_BRIDGE_SCRIPT", tmp_path / "nonexistent.mjs")
err = _ensure_cursor_bridge_deps()
assert err is not None
+
+
+def test_cursor_stream_buffers_merge_assistant(tmp_path: Path) -> None:
+ har = tmp_path / "recording.har"
+ har.write_text("{}")
+ with patch.dict("os.environ", {"CURSOR_API_KEY": "x"}):
+ with patch("reverse_api.cursor_engineer._ensure_cursor_bridge_deps", return_value=None):
+ eng = CursorEngineer(
+ run_id="r1",
+ har_path=har,
+ prompt="p",
+ cursor_model="composer-2",
+ sdk="cursor",
+ interactive=False,
+ verbose=False,
+ output_dir=str(tmp_path),
+ )
+ eng._cursor_reset_stream_buffers()
+ eng._cursor_feed_assistant("Hello")
+ eng._cursor_feed_assistant("Hello world")
+ assert eng._cursor_assistant_acc == "Hello world"
+ eng._cursor_feed_thinking(" t1")
+ eng._cursor_feed_thinking(" t2")
+ assert eng._cursor_thinking_acc == " t1 t2"
diff --git a/tests/test_tui.py b/tests/test_tui.py
index dcbb78c..5c9c4bc 100644
--- a/tests/test_tui.py
+++ b/tests/test_tui.py
@@ -123,11 +123,28 @@ class TestClaudeUI:
def test_thinking_truncation(self):
"""Long thinking text is truncated."""
ui, console = self._make_ui()
- long_text = "x" * 200
+ long_text = "x" * 600
ui.thinking(long_text)
output = console.file.getvalue()
assert "..." in output
+ def test_thinking_block_shows_full_block(self):
+ ui, console = self._make_ui()
+ ui.thinking_block("First paragraph.\n\nSecond paragraph.")
+ out = console.file.getvalue()
+ assert "First paragraph" in out
+ assert "Second paragraph" in out
+
+ def test_thinking_block_skipped_non_verbose(self):
+ ui, console = self._make_ui(verbose=False)
+ ui.thinking_block("Hidden block text")
+ assert console.file.getvalue().strip() == ""
+
+ def test_thinking_block_short_skipped(self):
+ ui, console = self._make_ui()
+ ui.thinking_block("x")
+ assert console.file.getvalue().strip() == ""
+
def test_progress(self):
"""Progress displays message."""
ui, console = self._make_ui()