#!/usr/bin/env python3 """Verifies `hd-joe ` end-to-end: run from inside an hd-managed tag directory with no explicit url/note-id/cookie, it should discover .hd/, create a new note tagged with the current directory's name the first time, and open the SAME note the second time -- all through real compiled JOE under a pty, against a combined fake server (history + download + new + realtime), not a mock of hd_core's own logic. """ import json import os import socket as socketmod import sys import threading import time from pathlib import Path import pexpect import socketio from werkzeug.serving import make_server from werkzeug.wrappers import Request, Response sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent.parent / "hd_common")) from hd_client import apply_operation from hd_core import Config, Cookies, parse_current_tags, parse_frontmatter 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 CombinedFakeServer: """history + download + new + realtime, one shared note store.""" def __init__(self, port): self.notes = {} # id -> {"content", "time", "revision"} self.port = port self.lock = threading.Lock() self._counter = 0 self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*") @self.sio.event def connect(sid, environ, auth): from urllib.parse import parse_qs qs = parse_qs(environ.get("QUERY_STRING", "")) note_id = (qs.get("noteId") or [None])[0] with self.lock: n = self.notes.get(note_id) if n is None: return self.sio.save_session(sid, {"note_id": note_id}) self.sio.emit("doc", {"str": n["content"], "revision": n["revision"], "clients": []}, to=sid) @self.sio.on("operation") def on_operation(sid, base_revision, operation, selection): with self.lock: session = self.sio.get_session(sid) note_id = session["note_id"] n = self.notes[note_id] if base_revision != n["revision"]: return try: n["content"] = apply_operation_strict(n["content"], operation) except Exception as exc: print("[fake server] rejected:", exc, operation) return n["revision"] += 1 n["time"] += 1 self.sio.emit("ack", n["revision"], to=sid) self._socketio_app = socketio.WSGIApp(self.sio) def wsgi(environ, start_response): request = Request(environ) if request.path == "/new" and request.method == "POST": with self.lock: self._counter += 1 note_id = f"minted-{self._counter}" body = request.get_data(as_text=True) self.notes[note_id] = {"content": body, "time": 1, "revision": 0} resp = Response(status=302, headers={"Location": f"/{note_id}"}) return resp(environ, start_response) if request.path == "/history": with self.lock: history = [] for nid, n in self.notes.items(): fm = parse_frontmatter(n["content"]) import yaml tags = parse_current_tags(yaml.safe_load(fm["yaml_str"]) or {}) if fm else [] title = (yaml.safe_load(fm["yaml_str"]) or {}).get("title", nid) if fm else nid history.append({"id": nid, "text": title, "tags": tags, "time": n["time"]}) resp = Response(json.dumps({"history": history}), mimetype="application/json") return resp(environ, start_response) if request.path.endswith("/download"): nid = request.path.split("/")[1] with self.lock: n = self.notes.get(nid) resp = Response(n["content"] if n else "", mimetype="text/markdown", status=200 if n else 404) return resp(environ, start_response) return self._socketio_app(environ, start_response) self.srv = make_server("127.0.0.1", port, wsgi, 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 run_hd_joe(cwd, name, extra_env=None): """Spawn `hd-joe ` (no url/note-id/cookie -- must auto-discover) with `cwd` as the working directory, type a marker, then quit.""" log_path = f"/tmp/hd-joe-create-{name.replace(' ', '_')}.log" sock_path = f"/tmp/hd-joe-create-{name.replace(' ', '_')}.sock" for p in (log_path, sock_path): try: os.remove(p) except OSError: pass cmd = f"python3 {AGENT} \"{name}\" --joe {JOE_BIN} --socket {sock_path} --log {log_path} --debug" env = {**os.environ, "TERM": "xterm"} if extra_env: env.update(extra_env) child = pexpect.spawn(cmd, cwd=str(cwd), env=env, dimensions=(24, 80), timeout=10) output_before = child.before time.sleep(1.2) # let discovery/creation + JOE startup + agent connect settle return child, log_path def main(): port = free_port() server = CombinedFakeServer(port) server.start() time.sleep(0.2) import tempfile, shutil tmpdir = Path(tempfile.mkdtemp(prefix="hd-joe-create-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) radio_dir = root / "radio" radio_dir.mkdir(parents=True) ok = True try: # --- First run: creates a new note tagged 'radio' --- child, log_path = run_hd_joe(radio_dir, "Fresh Project") child.send("hello from joe") time.sleep(0.6) child.send("\x0bx") time.sleep(0.4) child.send("\r") try: child.wait() except pexpect.TIMEOUT: pass if child.isalive(): child.terminate(force=True) time.sleep(0.3) symlink = radio_dir / "Fresh Project" print("symlink exists after first run:", symlink.is_symlink()) ok &= symlink.is_symlink() if len(server.notes) != 1: print(f"FAIL: expected exactly 1 note created, server has {len(server.notes)}: {list(server.notes)}") ok = False else: note_id = next(iter(server.notes)) content = server.notes[note_id]["content"] print("server content after first run:", repr(content[-60:])) ok &= "hello from joe" in content ok &= "tags: radio" in content # --- Second run, same name: must open the SAME note, not create another --- child2, log_path2 = run_hd_joe(radio_dir, "Fresh Project") time.sleep(0.5) child2.send("\x0bx") time.sleep(0.4) child2.send("\r") try: child2.wait() except pexpect.TIMEOUT: pass if child2.isalive(): child2.terminate(force=True) time.sleep(0.3) print("notes on server after second run:", len(server.notes)) ok &= len(server.notes) == 1 # still exactly one -- no duplicate created finally: server.stop() shutil.rmtree(tmpdir, ignore_errors=True) print("\nPASS" if ok else "\nFAIL") return 0 if ok else 1 if __name__ == "__main__": raise SystemExit(main())