first commit
This commit is contained in:
188
hd-joe/cursor_after_ai_test.py
Normal file
188
hd-joe/cursor_after_ai_test.py
Normal file
@@ -0,0 +1,188 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verifies the cursor-after-AI-update fix through the REAL pipeline: patched
|
||||
JOE under a pty + hd_joe_agent.py + fake server with a second ("AI") client.
|
||||
|
||||
Can't inspect JOE's on-screen cursor position directly, so the test proves
|
||||
it indirectly and unambiguously: after the AI's block-replace arrives, type
|
||||
a marker string into the (still-running) JOE session with no further
|
||||
navigation keys. If the cursor followed the fix, that marker lands right
|
||||
after "-> " in the final document. If it's still stuck at BOF (the bug),
|
||||
the marker lands at the very start instead.
|
||||
"""
|
||||
import os
|
||||
import socket as socketmod
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
import pexpect
|
||||
import socketio
|
||||
from werkzeug.serving import make_server
|
||||
|
||||
import sys as _sys
|
||||
from pathlib import Path as _Path
|
||||
_sys.path.insert(0, str(_Path(__file__).resolve().parent.parent / "hd_common"))
|
||||
|
||||
from hd_client import apply_operation
|
||||
|
||||
JOE_BIN = os.environ.get("JOE_BIN", "/home/claude/work/build/joe-4.8/joe/joe")
|
||||
AGENT = os.path.join(os.path.dirname(__file__), "hd_joe_agent.py")
|
||||
|
||||
|
||||
def apply_operation_strict(text, op):
|
||||
for c in op:
|
||||
if isinstance(c, bool):
|
||||
raise ValueError(f"unknown operation: {c!r}")
|
||||
if isinstance(c, int) and c == 0:
|
||||
raise ValueError(f"unknown operation: {c!r}")
|
||||
return apply_operation(text, op)
|
||||
|
||||
|
||||
class FakeServer:
|
||||
def __init__(self, initial_text, port):
|
||||
self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*")
|
||||
self.text = initial_text
|
||||
self.revision = 0
|
||||
self.lock = threading.Lock()
|
||||
|
||||
@self.sio.event
|
||||
def connect(sid, environ, auth):
|
||||
with self.lock:
|
||||
self.sio.emit("doc", {"str": self.text, "revision": self.revision, "clients": []}, to=sid)
|
||||
|
||||
@self.sio.on("operation")
|
||||
def on_operation(sid, base_revision, operation, selection):
|
||||
with self.lock:
|
||||
if base_revision != self.revision:
|
||||
return
|
||||
try:
|
||||
self.text = apply_operation_strict(self.text, operation)
|
||||
except Exception as exc:
|
||||
print("[fake server] rejected op:", exc, operation)
|
||||
return
|
||||
self.revision += 1
|
||||
self.sio.emit("ack", self.revision, to=sid)
|
||||
self.sio.emit("operation", (sid, self.revision, operation, selection, None), skip_sid=sid)
|
||||
|
||||
self.app = socketio.WSGIApp(self.sio)
|
||||
self.srv = make_server("127.0.0.1", port, self.app, threaded=True)
|
||||
self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True)
|
||||
|
||||
def start(self):
|
||||
self.thread.start()
|
||||
|
||||
def stop(self):
|
||||
self.srv.shutdown()
|
||||
|
||||
|
||||
def free_port():
|
||||
s = socketmod.socket(socketmod.AF_INET, socketmod.SOCK_STREAM)
|
||||
s.bind(("127.0.0.1", 0))
|
||||
port = s.getsockname()[1]
|
||||
s.close()
|
||||
return port
|
||||
|
||||
|
||||
def main():
|
||||
block = (
|
||||
"<!--Agent\n"
|
||||
"User: Funkar det med AI?\n"
|
||||
"Agent: Ja, det funkar! Jag kan lasa innehallet i ditt dokument och svara pa fragor baserat pa det.\n"
|
||||
"User: Fasen vad bra\n"
|
||||
"Agent: \U0001f9e0 Tanker...\n"
|
||||
"-->"
|
||||
)
|
||||
new_block = (
|
||||
"<!--Agent\n"
|
||||
"User: Funkar det med AI?\n"
|
||||
"Agent: Ja, det funkar! Jag kan lasa innehallet i ditt dokument och svara pa fragor baserat pa det.\n"
|
||||
"User: Fasen vad bra\n"
|
||||
"Agent: Visst ar det! Jag ser allt fran rubriken till din kommentar.\n"
|
||||
"->\n"
|
||||
"-->"
|
||||
)
|
||||
initial_text = "# Header\n\n" + block + "\n(some other text below)"
|
||||
assert len(block) > 100
|
||||
|
||||
port = free_port()
|
||||
server = FakeServer(initial_text, port)
|
||||
server.start()
|
||||
time.sleep(0.2)
|
||||
|
||||
sock_path = "/tmp/hd-joe-cursor-test.sock"
|
||||
log_path = "/tmp/hd-joe-cursor-test.log"
|
||||
for p in (sock_path, log_path):
|
||||
try:
|
||||
os.remove(p)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
cmd = (
|
||||
f"python3 {AGENT} http://127.0.0.1:{port} test-note "
|
||||
f"--joe {JOE_BIN} --socket {sock_path} --log {log_path} --debug"
|
||||
)
|
||||
child = pexpect.spawn(cmd, cwd=os.path.dirname(__file__), env={**os.environ, "TERM": "xterm"},
|
||||
dimensions=(24, 80), timeout=10)
|
||||
time.sleep(1.0)
|
||||
|
||||
# Simulate the AI's own connection replacing the whole block.
|
||||
import hd_client
|
||||
prefix = "# Header\n\n"
|
||||
suffix = "\n(some other text below)"
|
||||
op = [
|
||||
hd_client.utf16_len(prefix),
|
||||
-hd_client.utf16_len(block),
|
||||
new_block,
|
||||
hd_client.utf16_len(suffix),
|
||||
]
|
||||
ai = socketio.Client()
|
||||
ai.connect(f"http://127.0.0.1:{port}/?noteId=test-note", socketio_path="socket.io",
|
||||
transports=["websocket", "polling"])
|
||||
time.sleep(0.2)
|
||||
ai.emit("operation", (0, op, {"ranges": []}))
|
||||
time.sleep(0.8) # let the agent apply it and (if fixed) reposition the cursor
|
||||
|
||||
# No navigation keys at all -- type only. If the cursor followed the fix,
|
||||
# this lands right after "-> ". If it's stuck at BOF, it lands at the
|
||||
# very start of the document instead.
|
||||
marker = "MARKERTEXT"
|
||||
child.send(marker)
|
||||
time.sleep(0.6)
|
||||
|
||||
child.send("\x0bx")
|
||||
time.sleep(0.5)
|
||||
child.send("\r")
|
||||
try:
|
||||
child.wait()
|
||||
except pexpect.TIMEOUT:
|
||||
pass
|
||||
if child.isalive():
|
||||
child.terminate(force=True)
|
||||
time.sleep(0.3)
|
||||
|
||||
ai.disconnect()
|
||||
final_text = server.text
|
||||
server.stop()
|
||||
|
||||
print("Final server text:")
|
||||
print(repr(final_text))
|
||||
print()
|
||||
|
||||
expected_pos_text = "->\n" + marker # right after the prompt marker + newline... check both forms
|
||||
landed_after_prompt = (marker in final_text) and (
|
||||
final_text.find(marker) > final_text.find("Visst ar det")
|
||||
) and not final_text.startswith(marker)
|
||||
landed_at_bof = final_text.startswith(marker)
|
||||
|
||||
print("Marker landed at BOF (the bug):", landed_at_bof)
|
||||
print("Marker landed after the AI's answer (fixed):", landed_after_prompt)
|
||||
|
||||
if os.path.exists(log_path):
|
||||
print("\n--- agent log tail ---")
|
||||
print(open(log_path, encoding="utf-8", errors="replace").read()[-1500:])
|
||||
|
||||
sys.exit(0 if landed_after_prompt and not landed_at_bof else 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user