first commit

This commit is contained in:
Joakim
2026-10-15 17:27:46 +02:00
parent 0232909b8a
commit 0e0febffda
38 changed files with 8068 additions and 0 deletions

View File

@@ -0,0 +1,160 @@
#!/usr/bin/env python3
"""A genuine transport-level disconnect (server calls sio.disconnect(sid),
not just a shutdown()) forced mid-session, through a real pty-driven JOE.
Confirms: the agent's own client detects it (checked via its log, since
verbose logging already includes "Socket.IO disconnected."), and --
the actual point of this test -- JOE keeps working afterward: typing,
saving, and quitting cleanly, proving the new 'M' status-message command
doesn't crash or hang the editor when it arrives.
"""
import os
import shutil
import socket as socketmod
import sys
import tempfile
import threading
import time
from pathlib import Path
import pexpect
import socketio
from werkzeug.serving import make_server
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common"))
from hd_core import Config, Cookies, State, NoteState, content_hash
JOE_BIN = os.environ.get("JOE_BIN", "/home/claude/work/repo/joe-patch/build/joe-4.8/joe/joe")
AGENT = str(Path(__file__).resolve().parent / "hd_joe_agent.py")
class DisconnectableFakeServer:
def __init__(self, port, initial_text):
self.text = initial_text
self.sid = None
self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*")
@self.sio.event
def connect(sid, environ, auth):
self.sid = sid
self.sio.emit("doc", {"str": self.text, "revision": 0, "clients": []}, to=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 force_disconnect_client(self):
# A real server-initiated close, not shutting the whole server down
# -- reliably and promptly noticed by the client, unlike killing
# the whole listener (see test_offline_handling.py's docstring for
# why that one wasn't reliable within a short test timeout).
if self.sid:
self.sio.disconnect(self.sid)
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():
port = free_port()
note_id = "n1"
initial_content = "---\ntitle: Masten\ntags: sl6cv\n---\n\nbase content"
server = DisconnectableFakeServer(port, initial_content)
server.start()
time.sleep(0.2)
tmpdir = Path(tempfile.mkdtemp(prefix="hd-real-disconnect-test-"))
root = tmpdir / "notes"
hd_dir = root / ".hd"
(hd_dir / "notes").mkdir(parents=True)
Config(url=f"http://127.0.0.1:{port}", email=None).save(hd_dir)
Cookies(header="session=1").save(hd_dir)
state = State()
(hd_dir / "notes" / f"{note_id}.md").write_text(initial_content)
state.notes[note_id] = NoteState(
title="Masten", tags=["sl6cv"], symlinks={"sl6cv": "Masten"},
content_hash=content_hash(initial_content), last_seen_time=1,
)
state.save(hd_dir)
tag_dir = root / "sl6cv"
tag_dir.mkdir(parents=True)
(tag_dir / "Masten").symlink_to(Path("..") / ".hd" / "notes" / f"{note_id}.md")
ok = True
child = None
try:
log_path = "/tmp/hd-joe-real-disconnect.log"
try:
os.remove(log_path)
except OSError:
pass
cmd = f'python3 {AGENT} "Masten" --joe {JOE_BIN} --log {log_path} --debug'
env = {**os.environ, "TERM": "xterm", "HD_DRAIN_TIMEOUT": "2.0"}
child = pexpect.spawn(cmd, cwd=str(tag_dir), env=env, dimensions=(24, 80), timeout=15)
time.sleep(1.0)
# Force a REAL server-initiated disconnect mid-session -- this is
# what actually triggers _on_disconnect -> on_connection_state_changed
# -> Agent.send_message("M ...") being sent to JOE for real.
server.force_disconnect_client()
time.sleep(1.0)
# JOE must still be alive and responsive -- if the M command (or
# anything about handling the disconnect) crashed or hung it, this
# is where that would show up.
check1 = child.isalive()
print("JOE still alive after the disconnect + M command:", check1)
ok &= check1
child.send("\x0bv") # EOF
time.sleep(0.3)
child.send(" still typable after disconnect")
time.sleep(0.5)
child.send("\x0bx")
time.sleep(0.4)
child.send("\r")
try:
child.expect(pexpect.EOF, timeout=10)
except pexpect.TIMEOUT:
pass
rc = child.wait() if not child.isalive() else None
if child.isalive():
child.terminate(force=True)
time.sleep(0.3)
check2 = rc == 0 or rc is None # pexpect reports None if already reaped; either is a clean exit here
print("agent exited cleanly after the disconnect:", check2, "rc=", rc)
ok &= check2
log_text = Path(log_path).read_text() if Path(log_path).exists() else ""
check3 = "Socket.IO disconnected" in log_text
print("agent's own log confirms the disconnect was detected:", check3)
ok &= check3
finally:
if child and child.isalive():
child.terminate(force=True)
try:
server.stop()
except Exception:
pass
shutil.rmtree(tmpdir, ignore_errors=True)
print("\nPASS" if ok else "\nFAIL")
return 0 if ok else 1
if __name__ == "__main__":
raise SystemExit(main())