first commit
This commit is contained in:
71
hd-joe/README.md
Normal file
71
hd-joe/README.md
Normal file
@@ -0,0 +1,71 @@
|
||||
# hd-joe
|
||||
|
||||
The Python side of the terminal editor. Owns the Socket.IO/OT connection to
|
||||
HedgeDoc and drives a patched JOE over a private Unix socket.
|
||||
|
||||
Run `../install.sh` from the repo root first (builds patched JOE, sets up a
|
||||
venv, links `hdc` and `hd-joe` onto your PATH). This README covers `hd-joe`
|
||||
specifically once that's done; see the top-level README for the whole repo.
|
||||
|
||||
## Running
|
||||
|
||||
Two forms. The second needs an `hdc`-managed folder (see `../hd-cli/`); the
|
||||
first works anywhere.
|
||||
|
||||
# Explicit: any server, any note, no hdc setup needed
|
||||
hd-joe https://hedgedoc.example <note-id> --cookie 'connect.sid=...'
|
||||
|
||||
# From inside ~/notes/<tag>/ : reads .hd/config.json + cookies.json,
|
||||
# opens "Project" if a symlink for it exists here, else creates it
|
||||
# tagged with this directory's name
|
||||
cd ~/notes/radio
|
||||
hd-joe "Project"
|
||||
|
||||
Useful flags: `--debug` (verbose log), `--log PATH` (default
|
||||
`~/.local/state/picocalc/hd-joe.log`), `--buffer PATH` (keep the working
|
||||
file instead of a temp file), `--quiet`, `--joe PATH` (use a specific joe
|
||||
binary instead of the one `install.sh` put on PATH).
|
||||
|
||||
## Files
|
||||
|
||||
| File | |
|
||||
| --- | --- |
|
||||
| `hd-joe` | Entry point (thin `sh` wrapper around `hd_joe_agent.py`). |
|
||||
| `hd_joe_agent.py` | CLI, JOE subprocess management, the Unix-socket bridge, translating OT operations into JOE insert/delete commands. |
|
||||
| `joe_wrapper.py` | Installed AT the `joe` name (see top-level README's "The joe wrapper") -- routes hd-managed notes here, everything else to the real binary. `decide()` is the pure, tested routing logic; `run()`/`main()` just `exec` whatever it returns. |
|
||||
|
||||
`hd_client.py` (the OT engine) and `hd_core.py` (folder discovery, note
|
||||
creation, tag writing, reconciliation) live in `../hd_common/` — see
|
||||
`../hd_common/README.md`. Both this package and `../hd-cli/` import them
|
||||
from there; there's only one copy.
|
||||
|
||||
## Tests
|
||||
|
||||
No network or real server needed — they spin up fake HedgeDoc servers
|
||||
locally. The pty-driven ones need a built `joe`:
|
||||
|
||||
JOE_BIN=/path/to/joe-4.8/joe/joe python3 e2e_test.py # BOF/EOF edits
|
||||
ACK_DELAY=0.15 JOE_BIN=... python3 e2e_test.py # ...under latency
|
||||
python3 ai_replace_test.py # AI block replace
|
||||
JOE_BIN=... python3 cursor_after_ai_test.py # cursor after AI answer
|
||||
JOE_BIN=... python3 test_hd_joe_create.py # hd-joe <name> create/open
|
||||
JOE_BIN=... python3 test_hd_cache_refresh.py # cache updates after editing
|
||||
JOE_BIN=... python3 test_hd_cache_live_refresh.py # ...and while still open
|
||||
python3 test_hd_create.py # discovery/create logic
|
||||
python3 test_joe_wrapper.py # joe-vs-hd-joe routing logic
|
||||
JOE_BIN=... python3 test_joe_wrapper_exec.py # wrapper really execs real joe
|
||||
JOE_BIN=... python3 test_joe_wrapper_hdjoe_exec.py # ...and really execs hd-joe
|
||||
python3 test_disconnect_hook.py # connection-state hook fires correctly
|
||||
python3 test_shadow_text_sync.py # _shadow_text stays in sync even on error
|
||||
JOE_BIN=... HD_DRAIN_TIMEOUT=2.0 python3 test_offline_handling.py # offline: no cache poisoning, recovery file
|
||||
JOE_BIN=... python3 test_real_disconnect_pty.py # real disconnect, JOE survives the M command
|
||||
|
||||
`fake_hedgedoc.py` is a standalone fake server for poking at things by hand.
|
||||
|
||||
**These fake servers have been wrong three times.** Each time, real HedgeDoc
|
||||
did something the mock didn't: acked instantly (hid a rejected-operation
|
||||
bug), had no DB-flush lag (hid a stale-content bug), never broadcast to
|
||||
other clients (hid that whole category). They were patched after reality
|
||||
disagreed, not before. Treat a green test suite as necessary, not
|
||||
sufficient — and if you add coverage, make the fake stricter rather than
|
||||
more convenient.
|
||||
112
hd-joe/ai_replace_test.py
Normal file
112
hd-joe/ai_replace_test.py
Normal file
@@ -0,0 +1,112 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Reproduces the 'AI answer replaced with stale placeholder' bug:
|
||||
HedgeDoc's /download route reads DB-backed content that lags the live
|
||||
realtime document by up to ~1s. A client that reacts to a large remote
|
||||
delete by fetching /download instead of just applying the operation can
|
||||
apply a completely correct-looking BUT STALE snapshot, and never correct
|
||||
itself since it already advanced past that revision.
|
||||
|
||||
No JOE/pty involved -- this bug lives entirely in hd_client.py.
|
||||
"""
|
||||
import importlib
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
import socketio
|
||||
|
||||
sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent.parent / "hd_common"))
|
||||
from e2e_test import FakeServer, free_port # noqa: E402
|
||||
|
||||
|
||||
def build_scenario():
|
||||
prefix = "# Header\n\n"
|
||||
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"
|
||||
"-->"
|
||||
)
|
||||
suffix = "\n(end)"
|
||||
assert len(block) > 100, "test block must exceed the old >100-char large_delete threshold"
|
||||
return prefix, block, new_block, suffix
|
||||
|
||||
|
||||
def run(client_module_path):
|
||||
# Force a clean import of whichever hd_client.py variant is on disk right now.
|
||||
if "hd_client" in sys.modules:
|
||||
del sys.modules["hd_client"]
|
||||
hd_client = importlib.import_module("hd_client")
|
||||
|
||||
prefix, block, new_block, suffix = build_scenario()
|
||||
initial_text = prefix + block + suffix
|
||||
port = free_port()
|
||||
server = FakeServer(initial_text, port, db_flush_interval=1.0)
|
||||
server.start()
|
||||
time.sleep(0.2)
|
||||
|
||||
events = []
|
||||
client = hd_client.HedgeDocClient(
|
||||
f"http://127.0.0.1:{port}", "test-note", verbose=False,
|
||||
on_remote_operation=lambda doc: events.append(doc.text),
|
||||
)
|
||||
client.connect()
|
||||
doc = client.wait_ready()
|
||||
assert doc.text == initial_text
|
||||
|
||||
# Simulate the AI's own socket sending the block replacement, almost
|
||||
# immediately -- well inside the server's 1s DB-flush window.
|
||||
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.1)
|
||||
op = [
|
||||
hd_client.utf16_len(prefix),
|
||||
-hd_client.utf16_len(block),
|
||||
new_block,
|
||||
hd_client.utf16_len(suffix),
|
||||
]
|
||||
ai.emit("operation", (0, op, {"ranges": []}))
|
||||
time.sleep(0.4) # well before the 1.0s DB flush -- this is the race window
|
||||
|
||||
final_text = client.document.text
|
||||
client.close()
|
||||
ai.disconnect()
|
||||
server.stop()
|
||||
return final_text, new_block, initial_text
|
||||
|
||||
|
||||
def main():
|
||||
print("=" * 70)
|
||||
print("Testing hd_client.py as currently on disk")
|
||||
print("=" * 70)
|
||||
final_text, new_block, initial_text = run("hd_client")
|
||||
expected = initial_text.replace(
|
||||
initial_text[initial_text.index("<!--Agent"):initial_text.index("-->") + 3],
|
||||
new_block,
|
||||
)
|
||||
print("Got final client text ending:\n", repr(final_text[-160:]))
|
||||
print()
|
||||
print("Expected ending:\n", repr(expected[-160:]))
|
||||
ok = final_text == expected
|
||||
print()
|
||||
print("PASS" if ok else "FAIL", "-- AI answer applied correctly, not stuck on placeholder")
|
||||
if not ok:
|
||||
if "Tanker" in final_text:
|
||||
print("--> Stuck showing the 'Tanker...' placeholder: this IS the reported bug.")
|
||||
sys.exit(0 if ok else 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
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()
|
||||
265
hd-joe/e2e_test.py
Normal file
265
hd-joe/e2e_test.py
Normal file
@@ -0,0 +1,265 @@
|
||||
#!/usr/bin/env python3
|
||||
"""End-to-end regression test for the BOF/EOF local-insert bugs.
|
||||
|
||||
Runs the real patched JOE binary under a pty, driven by hd_joe_agent.py,
|
||||
against an in-process fake HedgeDoc server. No mocking of the OT engine or
|
||||
the C code: this is the actual compiled binary and the actual Python agent,
|
||||
exercised through real keystrokes.
|
||||
"""
|
||||
import json
|
||||
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
|
||||
|
||||
|
||||
def apply_operation_strict(text, op):
|
||||
"""Mirror ot.js's TextOperation.fromJSON validation exactly: a literal 0
|
||||
of any kind anywhere in the op is invalid ("unknown operation: 0") per
|
||||
isRetain/isInsert/isDelete in the real server's text-operation.js. This is
|
||||
what makes the fake server catch what hd_client.py's own (lenient)
|
||||
apply_operation does not -- it's the actual root cause of the BOF/EOF
|
||||
bugs: insert_operation/replace_operation used to always emit a trailing
|
||||
or leading 0 retain at the document boundaries.
|
||||
"""
|
||||
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)
|
||||
|
||||
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")
|
||||
|
||||
|
||||
class FakeServer:
|
||||
"""One fake-HedgeDoc instance on its own port, run in a background thread.
|
||||
|
||||
Also simulates HedgeDoc's real persistence model: the live OT document
|
||||
(self.text) and the DB-backed content served by /download (self.db_text)
|
||||
are DELIBERATELY not the same thing. Real HedgeDoc only flushes live ->
|
||||
DB once a second, and only if dirty (lib/realtime.js). db_flush_interval
|
||||
reproduces that lag so tests can catch code that wrongly treats
|
||||
/download as authoritative-and-current.
|
||||
"""
|
||||
|
||||
def __init__(self, initial_text, port, ack_delay=0.0, db_flush_interval=1.0):
|
||||
self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*")
|
||||
self.app = socketio.WSGIApp(self.sio)
|
||||
self.text = initial_text
|
||||
self.revision = 0
|
||||
self.operations = []
|
||||
self.rejections = []
|
||||
self.lock = threading.Lock()
|
||||
self.port = port
|
||||
self.ack_delay = ack_delay
|
||||
self.db_text = initial_text
|
||||
self._dirty = False
|
||||
self._stop_flush = threading.Event()
|
||||
|
||||
def flush_loop():
|
||||
while not self._stop_flush.wait(db_flush_interval):
|
||||
with self.lock:
|
||||
if self._dirty:
|
||||
self.db_text = self.text
|
||||
self._dirty = False
|
||||
|
||||
self.flush_thread = threading.Thread(target=flush_loop, daemon=True)
|
||||
|
||||
@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):
|
||||
if self.ack_delay:
|
||||
time.sleep(self.ack_delay) # simulate real network/server latency
|
||||
with self.lock:
|
||||
self.operations.append((base_revision, operation))
|
||||
if base_revision != self.revision:
|
||||
self.rejections.append((base_revision, operation, "bad base_revision"))
|
||||
return
|
||||
try:
|
||||
self.text = apply_operation_strict(self.text, operation)
|
||||
self._dirty = True
|
||||
except Exception as exc:
|
||||
self.rejections.append((base_revision, operation, repr(exc)))
|
||||
return
|
||||
self.revision += 1
|
||||
self.sio.emit("ack", self.revision, to=sid)
|
||||
# Real HedgeDoc broadcasts to every OTHER connected client in
|
||||
# the note's room (EditorSocketIOServer.onOperation:
|
||||
# socket.broadcast.in(this.docId).emit('operation', ...)).
|
||||
# Without this, a second connected client (e.g. an AI
|
||||
# integration, or another browser tab) never sees the edit --
|
||||
# which single-client tests can never catch.
|
||||
self.sio.emit(
|
||||
"operation",
|
||||
(sid, self.revision, operation, selection, None),
|
||||
skip_sid=sid,
|
||||
)
|
||||
|
||||
socketio_app = self.app
|
||||
|
||||
def wsgi_app(environ, start_response):
|
||||
path = environ.get("PATH_INFO", "")
|
||||
if path.endswith("/download"):
|
||||
with self.lock:
|
||||
body = self.db_text.encode("utf-8")
|
||||
start_response("200 OK", [
|
||||
("Content-Type", "text/markdown; charset=UTF-8"),
|
||||
("Content-Length", str(len(body))),
|
||||
])
|
||||
return [body]
|
||||
return socketio_app(environ, start_response)
|
||||
|
||||
self.app = wsgi_app
|
||||
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()
|
||||
self.flush_thread.start()
|
||||
|
||||
def stop(self):
|
||||
self._stop_flush.set()
|
||||
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_case(name, initial_text, keys, settle=0.6, ack_delay=0.0):
|
||||
port = free_port()
|
||||
server = FakeServer(initial_text, port, ack_delay=ack_delay)
|
||||
server.start()
|
||||
time.sleep(0.2)
|
||||
|
||||
log_path = f"/tmp/hd-joe-{name}.log"
|
||||
sock_path = f"/tmp/hd-joe-{name}.sock"
|
||||
for p in (log_path, sock_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) # let JOE start, agent connect, initial doc load
|
||||
|
||||
for item in keys:
|
||||
if isinstance(item, float):
|
||||
time.sleep(item)
|
||||
elif isinstance(item, tuple) and item[0] == "burst":
|
||||
# Send a whole string in one write with no inter-key settle,
|
||||
# simulating continuous fast typing rather than one keystroke
|
||||
# at a time.
|
||||
child.send(item[1])
|
||||
else:
|
||||
child.send(item)
|
||||
time.sleep(0.15)
|
||||
|
||||
time.sleep(settle)
|
||||
|
||||
# Quit JOE: Ctrl-K X (save+exit). Send twice in case of an intervening prompt.
|
||||
child.send("\x0bx")
|
||||
time.sleep(0.5)
|
||||
child.send("\r")
|
||||
# Give the agent time to drain its pending queue and exit on its own
|
||||
# (it now blocks on this deliberately) before falling back to a kill.
|
||||
try:
|
||||
child.wait()
|
||||
except pexpect.TIMEOUT:
|
||||
pass
|
||||
if child.isalive():
|
||||
child.terminate(force=True)
|
||||
|
||||
time.sleep(0.3)
|
||||
server.stop()
|
||||
|
||||
log_tail = ""
|
||||
if os.path.exists(log_path):
|
||||
with open(log_path, encoding="utf-8", errors="replace") as f:
|
||||
log_tail = f.read()[-4000:]
|
||||
|
||||
return {
|
||||
"server_text": server.text,
|
||||
"server_revision": server.revision,
|
||||
"operations": server.operations,
|
||||
"rejections": server.rejections,
|
||||
"log_tail": log_tail,
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
print("=" * 70)
|
||||
print("TEST A: insert newline at BOF (top-of-file), expect first char kept")
|
||||
print("=" * 70)
|
||||
a = run_case(
|
||||
"bof",
|
||||
initial_text="helloworld",
|
||||
keys=["\r"], # cursor starts at BOF on a fresh file; press Enter
|
||||
)
|
||||
print("server text repr:", repr(a["server_text"]))
|
||||
print("server revision:", a["server_revision"])
|
||||
print("operations sent:", a["operations"])
|
||||
print("rejections:", a["rejections"])
|
||||
expected = "\nhelloworld"
|
||||
ok_a = a["server_text"] == expected
|
||||
print("EXPECTED:", repr(expected))
|
||||
print("PASS" if ok_a else "FAIL", "- BOF test")
|
||||
print()
|
||||
|
||||
print("=" * 70)
|
||||
print("TEST B: type a character at EOF, expect it to reach the server")
|
||||
print("=" * 70)
|
||||
b = run_case(
|
||||
"eof",
|
||||
initial_text="helloworld",
|
||||
keys=["\x0bv", 0.3, ("burst", "continued typing")], # Ctrl-K V = goto EOF, then type continuously
|
||||
settle=1.5,
|
||||
ack_delay=float(os.environ.get("ACK_DELAY", "0")),
|
||||
)
|
||||
print("server text repr:", repr(b["server_text"]))
|
||||
print("server revision:", b["server_revision"])
|
||||
print("operations sent:", b["operations"])
|
||||
print("rejections:", b["rejections"])
|
||||
expected_b = "helloworldcontinued typing"
|
||||
ok_b = b["server_text"] == expected_b
|
||||
print("EXPECTED:", repr(expected_b))
|
||||
print("PASS" if ok_b else "FAIL", "- EOF test")
|
||||
|
||||
if not ok_a:
|
||||
print("\n--- bof agent log tail ---")
|
||||
print(a["log_tail"])
|
||||
if not ok_b:
|
||||
print("\n--- eof agent log tail ---")
|
||||
print(b["log_tail"])
|
||||
|
||||
sys.exit(0 if (ok_a and ok_b) else 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
88
hd-joe/fake_hedgedoc.py
Normal file
88
hd-joe/fake_hedgedoc.py
Normal file
@@ -0,0 +1,88 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Minimal fake HedgeDoc 1.x realtime server: just enough Socket.IO wire
|
||||
protocol (doc / operation / ack) to drive hd_client.py end-to-end without a
|
||||
real HedgeDoc instance. Single-client, no peer broadcast -- sufficient to
|
||||
reproduce and verify the BOF/EOF local-edit bugs, which don't need
|
||||
concurrency to manifest.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
|
||||
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, utf16_len
|
||||
|
||||
|
||||
def apply_operation_strict(text, op):
|
||||
"""Mirror ot.js's TextOperation.fromJSON: a literal 0 anywhere in the op
|
||||
is invalid and must raise -- matches isRetain/isInsert/isDelete in the
|
||||
real server's text-operation.js."""
|
||||
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)
|
||||
|
||||
sio = socketio.Server(async_mode="threading", cors_allowed_origins="*")
|
||||
app = socketio.WSGIApp(sio)
|
||||
|
||||
state = {"text": "", "revision": 0}
|
||||
state_lock = threading.Lock()
|
||||
operations_received = [] # for test assertions
|
||||
|
||||
|
||||
@sio.event
|
||||
def connect(sid, environ, auth):
|
||||
with state_lock:
|
||||
sio.emit("doc", {"str": state["text"], "revision": state["revision"], "clients": []}, to=sid)
|
||||
|
||||
|
||||
@sio.on("operation")
|
||||
def on_operation(sid, base_revision, operation, selection):
|
||||
with state_lock:
|
||||
operations_received.append((base_revision, operation, selection))
|
||||
if base_revision != state["revision"]:
|
||||
# In this single-client test harness this should never happen.
|
||||
sys.stderr.write(
|
||||
f"[fake_hedgedoc] REJECTED operation: base_revision={base_revision} "
|
||||
f"!= server revision={state['revision']} op={operation!r}\n"
|
||||
)
|
||||
return
|
||||
try:
|
||||
state["text"] = apply_operation_strict(state["text"], operation)
|
||||
except Exception as exc:
|
||||
sys.stderr.write(f"[fake_hedgedoc] operation raised: {exc!r} op={operation!r}\n")
|
||||
return
|
||||
state["revision"] += 1
|
||||
sio.emit("ack", state["revision"], to=sid)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--port", type=int, default=5999)
|
||||
ap.add_argument("--text", default="")
|
||||
ap.add_argument("--state-file", help="write final {text, revision} as JSON here on SIGTERM/exit")
|
||||
args = ap.parse_args()
|
||||
state["text"] = args.text
|
||||
|
||||
srv = make_server("127.0.0.1", args.port, app)
|
||||
try:
|
||||
srv.serve_forever()
|
||||
finally:
|
||||
if args.state_file:
|
||||
with state_lock:
|
||||
with open(args.state_file, "w", encoding="utf-8") as f:
|
||||
json.dump({"text": state["text"], "revision": state["revision"],
|
||||
"operations": operations_received}, f)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
3
hd-joe/hd-joe
Executable file
3
hd-joe/hd-joe
Executable file
@@ -0,0 +1,3 @@
|
||||
#!/bin/sh
|
||||
SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
|
||||
exec python3 "$SCRIPT_DIR/hd_joe_agent.py" "$@"
|
||||
542
hd-joe/hd_joe_agent.py
Normal file
542
hd-joe/hd_joe_agent.py
Normal file
@@ -0,0 +1,542 @@
|
||||
#!/usr/bin/env python3
|
||||
"""HedgeDoc 1.x <-> patched JOE 4.8 agent 0.7.17.
|
||||
|
||||
The agent owns the Socket.IO/OT connection. Patched JOE owns the real editor
|
||||
buffer. They communicate over a private Unix stream socket.
|
||||
|
||||
Usage:
|
||||
hd-joe <url> <note-id> [--cookie ...] ... explicit, works anywhere
|
||||
hd-joe <name> ... inside an hd-managed folder:
|
||||
opens NAME if a symlink for
|
||||
it already exists in the
|
||||
current tag directory,
|
||||
otherwise creates a new note
|
||||
tagged with that directory's
|
||||
name (see hd_core.py's
|
||||
find_hd_root/tag_from_cwd/
|
||||
resolve_or_create_note)
|
||||
|
||||
JOE -> agent:
|
||||
I <byte-offset> <hex-bytes>
|
||||
D <byte-offset> <byte-count>
|
||||
|
||||
agent -> JOE:
|
||||
I <byte-offset> <hex-bytes>
|
||||
D <byte-offset> <byte-count>
|
||||
R <hex-utf8> replace the entire JOE buffer atomically
|
||||
C <byte-offset> move the cursor (used after an AI/agent block
|
||||
rewrite, to land back at the next input prompt)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import argparse, json, logging, os, socket, subprocess, sys, tempfile, threading, time
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
# hd_core.py/hd_client.py live in ../hd_common, shared verbatim with hd-cli
|
||||
# (see hd_common/README.md) -- add it to sys.path before importing either,
|
||||
# regardless of where this script is actually invoked from.
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common"))
|
||||
|
||||
import hd_core
|
||||
import joe_wrapper
|
||||
from hd_client import HedgeDocClient, HedgeDocDocument, Operation
|
||||
|
||||
logger = logging.getLogger("picocalc.hd")
|
||||
|
||||
|
||||
def byte_to_char(s: str, byte_pos: int) -> int:
|
||||
if byte_pos < 0:
|
||||
raise ValueError("negative byte position")
|
||||
raw = s.encode("utf-8")
|
||||
if byte_pos > len(raw):
|
||||
raise ValueError("byte position outside document")
|
||||
try:
|
||||
return len(raw[:byte_pos].decode("utf-8"))
|
||||
except UnicodeDecodeError as e:
|
||||
raise ValueError("JOE position is not on a UTF-8 character boundary") from e
|
||||
|
||||
|
||||
def byte_range_to_text(s: str, pos: int, length: int) -> tuple[int, int]:
|
||||
raw = s.encode("utf-8")
|
||||
if pos < 0 or length < 0 or pos + length > len(raw):
|
||||
raise ValueError("byte range outside document")
|
||||
try:
|
||||
a = len(raw[:pos].decode("utf-8"))
|
||||
b = len(raw[:pos+length].decode("utf-8"))
|
||||
except UnicodeDecodeError as e:
|
||||
raise ValueError("JOE range is not UTF-8 aligned") from e
|
||||
return a, b
|
||||
|
||||
|
||||
def op_to_joe_commands(old_text: str, op: Operation):
|
||||
"""Convert a HedgeDoc UTF-16 OT operation into JOE byte edits."""
|
||||
source_u = 0
|
||||
byte_pos = 0
|
||||
doc_u = len(old_text.encode("utf-16-le")) // 2
|
||||
out = []
|
||||
for c in op:
|
||||
if isinstance(c, bool):
|
||||
raise ValueError("invalid OT bool")
|
||||
if isinstance(c, int):
|
||||
if c >= 0:
|
||||
end_u = source_u + c
|
||||
if end_u > doc_u:
|
||||
raise ValueError("retain exceeds document")
|
||||
from hd_client import utf16_to_char_index
|
||||
a = utf16_to_char_index(old_text, source_u)
|
||||
b = utf16_to_char_index(old_text, end_u)
|
||||
segment = old_text[a:b]
|
||||
byte_pos += len(segment.encode("utf-8"))
|
||||
source_u = end_u
|
||||
else:
|
||||
n = -c
|
||||
end_u = source_u + n
|
||||
if end_u > doc_u:
|
||||
raise ValueError("delete exceeds document")
|
||||
from hd_client import utf16_to_char_index
|
||||
a = utf16_to_char_index(old_text, source_u)
|
||||
b = utf16_to_char_index(old_text, end_u)
|
||||
deleted = old_text[a:b]
|
||||
out.append(("D", byte_pos, len(deleted.encode("utf-8"))))
|
||||
source_u = end_u
|
||||
continue
|
||||
if isinstance(c, str):
|
||||
raw = c.encode("utf-8")
|
||||
if raw:
|
||||
out.append(("I", byte_pos, raw))
|
||||
byte_pos += len(raw)
|
||||
continue
|
||||
raise ValueError(f"invalid OT component {c!r}")
|
||||
if source_u != doc_u:
|
||||
raise ValueError("OT did not consume document")
|
||||
return out
|
||||
|
||||
|
||||
class Agent:
|
||||
def __init__(self, client: HedgeDocClient, sock_path: Path, buffer_path: Path,
|
||||
hd_root: Optional[Path] = None, note_id: Optional[str] = None):
|
||||
self.client = client
|
||||
self.sock_path = sock_path
|
||||
self.buffer_path = buffer_path
|
||||
self.server: Optional[socket.socket] = None
|
||||
self.conn: Optional[socket.socket] = None
|
||||
self.stop = threading.Event()
|
||||
self.lock = threading.RLock()
|
||||
self.rx = b""
|
||||
self.hd_root = hd_root
|
||||
self.note_id = note_id
|
||||
self._last_cache_write = 0.0
|
||||
client.on_remote_operation_detail = self.remote_operation
|
||||
client.on_connection_state_changed = self.on_connection_state_changed
|
||||
|
||||
def send_cmd(self, kind, pos, payload):
|
||||
c = self.conn
|
||||
if not c:
|
||||
return
|
||||
if kind == "I":
|
||||
line = f"I {pos} {payload.hex()}\n".encode()
|
||||
else:
|
||||
line = f"D {pos} {payload}\n".encode()
|
||||
try:
|
||||
with self.lock:
|
||||
c.sendall(line)
|
||||
except OSError:
|
||||
self.stop.set()
|
||||
|
||||
def replace_buffer(self, text: str):
|
||||
"""Ask JOE to replace its entire buffer in one atomic editor-side
|
||||
operation. No longer called from remote_operation() (see below --
|
||||
it was the cause of the cursor-jumps-to-BOF bug), kept as a
|
||||
primitive for a future hard-resync path."""
|
||||
c = self.conn
|
||||
if not c:
|
||||
return
|
||||
raw = text.encode("utf-8")
|
||||
line = b"R " + raw.hex().encode("ascii") + b"\n"
|
||||
try:
|
||||
with self.lock:
|
||||
c.sendall(line)
|
||||
except OSError:
|
||||
self.stop.set()
|
||||
|
||||
def send_cursor(self, byte_pos: int):
|
||||
c = self.conn
|
||||
if not c:
|
||||
return
|
||||
line = f"C {byte_pos}\n".encode()
|
||||
try:
|
||||
with self.lock:
|
||||
c.sendall(line)
|
||||
except OSError:
|
||||
self.stop.set()
|
||||
|
||||
def send_message(self, text: str):
|
||||
c = self.conn
|
||||
if not c:
|
||||
return
|
||||
line = b"M " + text.encode("utf-8").hex().encode("ascii") + b"\n"
|
||||
try:
|
||||
with self.lock:
|
||||
c.sendall(line)
|
||||
except OSError:
|
||||
self.stop.set()
|
||||
|
||||
def on_connection_state_changed(self, connected: bool):
|
||||
# Called from hd_client's Socket.IO thread, not JOE's socket thread
|
||||
# -- send_message() takes self.lock itself, same as every other
|
||||
# command sent to JOE, so this is safe to call from either.
|
||||
if connected:
|
||||
self.send_message("Back online -- syncing resumed.")
|
||||
else:
|
||||
self.send_message("OFFLINE -- edits are NOT being saved to the server.")
|
||||
|
||||
# Marker the HedgeDoc AI mod uses for its input prompt (see hd-joe README /
|
||||
# the user's own description: "man skriver vid -> och tva enter skickar").
|
||||
AGENT_PROMPT_MARKER = "\n->"
|
||||
|
||||
def _agent_prompt_byte_pos(self, text: str):
|
||||
"""Byte offset right after the next-message prompt marker, if present."""
|
||||
idx = text.rfind(self.AGENT_PROMPT_MARKER)
|
||||
if idx == -1:
|
||||
return None
|
||||
char_pos = idx + len(self.AGENT_PROMPT_MARKER)
|
||||
if text[char_pos:char_pos + 1] == " ":
|
||||
char_pos += 1
|
||||
return len(text[:char_pos].encode("utf-8"))
|
||||
|
||||
def remote_operation(self, doc: HedgeDocDocument, op: Operation):
|
||||
# The client has already transformed/applied op to produce doc.text.
|
||||
with self.lock:
|
||||
old = getattr(self, "_shadow_text", None)
|
||||
if old is None:
|
||||
self._shadow_text = doc.text
|
||||
if self.conn is None:
|
||||
self.buffer_path.write_text(doc.text, encoding="utf-8")
|
||||
return
|
||||
# A delete this large is very likely a HedgeDoc AI/agent
|
||||
# integration rewriting its whole block (placeholder -> answer).
|
||||
# This only decides where we put the cursor afterward -- the
|
||||
# buffer update itself always goes through the incremental path
|
||||
# below, never a whole-buffer replace, which is what used to
|
||||
# send the cursor to BOF: bdel() on the entire buffer collapses
|
||||
# every pointer in it -- including the cursor -- to byte 0, with
|
||||
# no way back. Incremental D+I commands only touch the pointers
|
||||
# inside the actually-changed range.
|
||||
large_delete = any(isinstance(c, int) and c < -100 for c in op)
|
||||
try:
|
||||
cmds = op_to_joe_commands(old, op)
|
||||
for kind, pos, data in cmds:
|
||||
self.send_cmd(kind, pos, data)
|
||||
self._shadow_text = doc.text
|
||||
except Exception:
|
||||
logger.exception("Cannot translate remote OT for JOE")
|
||||
return
|
||||
if large_delete:
|
||||
cursor_pos = self._agent_prompt_byte_pos(doc.text)
|
||||
if cursor_pos is not None:
|
||||
self.send_cursor(cursor_pos)
|
||||
|
||||
# Keep the local mirror reasonably fresh while a session is open,
|
||||
# not just at quit -- so someone else's edits (via webUI, say)
|
||||
# show up if you `cat` the symlink mid-session, not only after
|
||||
# you close JOE. Throttled to at most once/second: each write
|
||||
# takes the same interprocess lock `hdc sync` uses and rewrites
|
||||
# state.json, which isn't free, and a fast remote typist would
|
||||
# otherwise trigger it on every keystroke. The quit-time
|
||||
# update_note_cache() call already guarantees a final, fully
|
||||
# up-to-date write regardless of this throttle.
|
||||
if self.hd_root and self.note_id:
|
||||
now = time.monotonic()
|
||||
if now - self._last_cache_write >= 1.0:
|
||||
self._last_cache_write = now
|
||||
try:
|
||||
hd_core.update_note_cache(self.hd_root, self.note_id, doc.text)
|
||||
except Exception:
|
||||
logger.exception("Could not refresh local cache for %s", self.note_id)
|
||||
|
||||
def handle_local(self, line: str):
|
||||
parts = line.split(" ", 2)
|
||||
if not parts or parts[0] not in ("I", "D"):
|
||||
return
|
||||
try:
|
||||
kind = parts[0]
|
||||
pos = int(parts[1])
|
||||
with self.lock:
|
||||
text = self.client.document.text
|
||||
if kind == "I":
|
||||
raw = bytes.fromhex(parts[2].strip())
|
||||
ins = raw.decode("utf-8")
|
||||
cp = byte_to_char(text, pos)
|
||||
self.client.insert(cp, ins)
|
||||
else:
|
||||
n = int(parts[2])
|
||||
a, b = byte_range_to_text(text, pos, n)
|
||||
self.client.send_operation(self._delete_op(text, a, b))
|
||||
except Exception:
|
||||
# Covers the offline case among others: send_operation() already
|
||||
# updated self.client.document.text optimistically (that's why
|
||||
# local editing keeps working while disconnected) *before*
|
||||
# _emit_pending()'s socket.emit() raises BadNamespaceError -- so
|
||||
# this can fire with the local edit already applied in memory.
|
||||
logger.exception("Local JOE edit rejected")
|
||||
finally:
|
||||
# Must run whether or not the block above raised: document.text
|
||||
# may already have moved (see above), and if _shadow_text isn't
|
||||
# kept in sync with it, the NEXT remote operation gets translated
|
||||
# into JOE IPC commands against a stale baseline -- a corruption
|
||||
# risk, not just a lost-edit one.
|
||||
self._shadow_text = self.client.document.text
|
||||
|
||||
@staticmethod
|
||||
def _delete_op(text: str, a: int, b: int):
|
||||
# a, b are Python character indices (from byte_range_to_text); every
|
||||
# other op in this file is built in UTF-16 code units via utf16_len.
|
||||
# Real HedgeDoc (ot.js) rejects a literal 0 anywhere in the op array
|
||||
# ("unknown operation: 0") -- zero-length retains must be omitted,
|
||||
# not sent as 0, exactly like insert_operation/replace_operation.
|
||||
from hd_client import utf16_len
|
||||
a_u = utf16_len(text[:a])
|
||||
b_u = utf16_len(text[:b])
|
||||
tail_u = utf16_len(text) - b_u
|
||||
op = []
|
||||
if a_u:
|
||||
op.append(a_u)
|
||||
op.append(-(b_u - a_u))
|
||||
if tail_u:
|
||||
op.append(tail_u)
|
||||
return op
|
||||
|
||||
def serve(self):
|
||||
self.sock_path.unlink(missing_ok=True)
|
||||
self.server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
self.server.bind(str(self.sock_path))
|
||||
self.server.listen(1)
|
||||
self.server.settimeout(0.5)
|
||||
try:
|
||||
while not self.stop.is_set():
|
||||
try:
|
||||
c,_ = self.server.accept()
|
||||
except socket.timeout:
|
||||
continue
|
||||
self.conn = c
|
||||
self._shadow_text = self.client.document.text
|
||||
c.settimeout(0.5)
|
||||
buf = b""
|
||||
while not self.stop.is_set():
|
||||
try:
|
||||
data = c.recv(65536)
|
||||
except socket.timeout:
|
||||
continue
|
||||
if not data:
|
||||
break
|
||||
buf += data
|
||||
while b"\n" in buf:
|
||||
raw, buf = buf.split(b"\n",1)
|
||||
if raw:
|
||||
self.handle_local(raw.decode("ascii"))
|
||||
try: c.close()
|
||||
except OSError: pass
|
||||
self.conn = None
|
||||
break
|
||||
finally:
|
||||
self.stop.set()
|
||||
if self.server:
|
||||
self.server.close()
|
||||
self.sock_path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def drain_pending(client: HedgeDocClient, timeout: float = 15.0, poll: float = 0.05) -> bool:
|
||||
"""Block until every locally queued operation has been ACKed, or timeout.
|
||||
|
||||
JOE exiting only ends the editor process; the agent's Socket.IO
|
||||
connection to HedgeDoc keeps running in its own thread and will still
|
||||
receive ACKs for anything still in the local pending queue. The only
|
||||
thing that was silently discarding typed-but-unacked text was closing
|
||||
that connection immediately after JOE exited, instead of waiting for
|
||||
the queue to actually drain first.
|
||||
"""
|
||||
import time
|
||||
deadline = time.monotonic() + timeout
|
||||
last_count = client.pending_count
|
||||
if last_count:
|
||||
logger.info("Draining %d unsent local operation(s) before exit...", last_count)
|
||||
while client.pending_count > 0:
|
||||
if time.monotonic() >= deadline:
|
||||
logger.error(
|
||||
"Exiting with %d local operation(s) still unacknowledged after "
|
||||
"%.1fs drain timeout -- these were NOT saved to the server.",
|
||||
client.pending_count, timeout,
|
||||
)
|
||||
return False
|
||||
time.sleep(poll)
|
||||
if last_count:
|
||||
logger.info("Drain complete: all local operations acknowledged.")
|
||||
return True
|
||||
|
||||
|
||||
def main():
|
||||
ap=argparse.ArgumentParser(
|
||||
description="Run patched JOE as a HedgeDoc editor",
|
||||
epilog="Either give an explicit '<url> <note-id>', or a single NAME to "
|
||||
"open-or-create inside an hd-managed folder (see hd_core.find_hd_root) "
|
||||
"-- run from inside ~/notes/<tag>/ for that second form.",
|
||||
)
|
||||
ap.add_argument("target", nargs="+", metavar="URL NOTE_ID | NAME")
|
||||
ap.add_argument("--cookie")
|
||||
# Default points at the real compiled binary directly, not bare "joe"
|
||||
# resolved via PATH: once joe_wrapper.py is installed AT the "joe" name
|
||||
# (see install.sh), a bare "joe" would loop back into that wrapper.
|
||||
# This subprocess call is always meant to reach the real editor, so it
|
||||
# names it explicitly rather than relying on the wrapper's own (correct
|
||||
# but incidental) handling of "an existing plain file, not an hd note"
|
||||
# to avoid recursing.
|
||||
_default_joe = joe_wrapper.DEFAULT_REAL_JOE if Path(joe_wrapper.DEFAULT_REAL_JOE).exists() else "joe"
|
||||
ap.add_argument("--joe", default=_default_joe)
|
||||
ap.add_argument("--socket")
|
||||
ap.add_argument("--buffer", help="persistent working file")
|
||||
ap.add_argument("--quiet", action="store_true", help="disable normal log messages")
|
||||
ap.add_argument("--log", help="log file (default: ~/.local/state/picocalc/hd-joe.log)")
|
||||
ap.add_argument("--debug", action="store_true", help="verbose debug logging")
|
||||
args=ap.parse_args()
|
||||
if len(args.target) not in (1, 2):
|
||||
ap.error("expected either 'URL NOTE_ID' or a single NAME")
|
||||
|
||||
log_path = Path(args.log).expanduser() if args.log else Path("~/.local/state/picocalc/hd-joe.log").expanduser()
|
||||
if not args.quiet:
|
||||
log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
handler = logging.FileHandler(log_path, encoding="utf-8")
|
||||
handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s"))
|
||||
logger.setLevel(logging.DEBUG if args.debug else logging.INFO)
|
||||
logger.handlers.clear()
|
||||
logger.addHandler(handler)
|
||||
logger.propagate = False
|
||||
else:
|
||||
logger.handlers.clear()
|
||||
logger.addHandler(logging.NullHandler())
|
||||
logger.setLevel(logging.CRITICAL)
|
||||
|
||||
# Resolve what to actually connect to. Two explicit args always win and
|
||||
# never need .hd/ at all (a server with no local login, or hd-joe used
|
||||
# standalone outside any hd-managed folder). A single NAME requires an
|
||||
# .hd/ directory somewhere above the current directory, git-style.
|
||||
cwd = Path.cwd()
|
||||
hd_root = hd_core.find_hd_root(cwd)
|
||||
hd_dir = hd_root / ".hd" if hd_root else None
|
||||
discovered_cookie = None
|
||||
if hd_dir:
|
||||
try:
|
||||
discovered_cookie = hd_core.Cookies.load(hd_dir).header
|
||||
except (FileNotFoundError, json.JSONDecodeError, KeyError):
|
||||
discovered_cookie = None
|
||||
|
||||
if len(args.target) == 2:
|
||||
url, note_id = args.target
|
||||
cookie = args.cookie or discovered_cookie # may legitimately be None -- unauthenticated notes exist
|
||||
else:
|
||||
name = args.target[0]
|
||||
if hd_root is None:
|
||||
print(f"'{name}' isn't 'URL NOTE_ID', and no .hd/ directory was found "
|
||||
f"above {cwd} -- run 'hdc init' first, or pass both explicitly.",
|
||||
file=sys.stderr)
|
||||
return 1
|
||||
config = hd_core.Config.load(hd_dir)
|
||||
cookie = args.cookie or discovered_cookie
|
||||
if not cookie:
|
||||
print(f"{hd_dir / 'cookies.json'} has no usable cookie -- re-run 'hdc init'.",
|
||||
file=sys.stderr)
|
||||
return 1
|
||||
|
||||
problems = hd_core.load_problems(hd_dir)
|
||||
if problems:
|
||||
print(f"{len(problems)} problem(s) from the last 'hdc sync':", file=sys.stderr)
|
||||
for p in problems:
|
||||
print(f" - {p}", file=sys.stderr)
|
||||
print(file=sys.stderr)
|
||||
|
||||
try:
|
||||
note_id, created = hd_core.resolve_or_create_note(hd_root, cwd, name, config.url, cookie)
|
||||
except ValueError as exc:
|
||||
print(f"Refusing: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
url = config.url
|
||||
if created:
|
||||
print(f"Created new note '{name}' -- id {note_id}")
|
||||
|
||||
client=HedgeDocClient(url,note_id,cookie=cookie,verbose=not args.quiet)
|
||||
sock=Path(args.socket or f"/tmp/joe-hedgedoc-{os.getpid()}.sock")
|
||||
persistent=Path(args.buffer).expanduser() if args.buffer else None
|
||||
tmp=None
|
||||
proc=None
|
||||
agent=None
|
||||
try:
|
||||
client.connect()
|
||||
doc=client.wait_ready()
|
||||
if persistent:
|
||||
persistent.parent.mkdir(parents=True,exist_ok=True)
|
||||
persistent.write_text(doc.text,encoding="utf-8")
|
||||
path=persistent
|
||||
else:
|
||||
fd,name_=tempfile.mkstemp(prefix=f"hedgedoc-{note_id}-",suffix=".md")
|
||||
os.close(fd); tmp=Path(name_)
|
||||
tmp.write_text(doc.text,encoding="utf-8"); path=tmp
|
||||
|
||||
agent=Agent(client,sock,path,hd_root=hd_root,note_id=note_id)
|
||||
th=threading.Thread(target=agent.serve,daemon=True)
|
||||
th.start()
|
||||
|
||||
env=os.environ.copy()
|
||||
env["JOE_HEDGE_SOCKET"]=str(sock)
|
||||
env["JOE_HEDGE_BUFFER"]=str(path)
|
||||
proc=subprocess.Popen([args.joe,str(path)],env=env)
|
||||
rc=proc.wait()
|
||||
agent.stop.set()
|
||||
fully_synced = drain_pending(client, timeout=float(os.environ.get("HD_DRAIN_TIMEOUT", "15.0")))
|
||||
if hd_root:
|
||||
if fully_synced:
|
||||
try:
|
||||
hd_core.update_note_cache(hd_root, note_id, client.document.text)
|
||||
except Exception:
|
||||
logger.exception("Could not refresh local cache for %s", note_id)
|
||||
else:
|
||||
# Do NOT write client.document.text here: it's the locally
|
||||
# optimistic buffer, but the server never acknowledged it
|
||||
# (still offline, most likely). Writing it into the cache
|
||||
# anyway, with a matching content_hash, would tell every
|
||||
# future 'hdc sync' this note is already up to date -- the
|
||||
# skip-fetch check (state.json's last_seen_time == /history's
|
||||
# time) would then never re-fetch it, permanently hiding a
|
||||
# real divergence from the server behind a false "in sync".
|
||||
# Leaving the tracked cache untouched means the next
|
||||
# successful sync still sees the truth -- but the user's
|
||||
# actual keystrokes still shouldn't just vanish because of
|
||||
# that, so they're saved to a separate, untracked recovery
|
||||
# file instead. JOE's process has already exited by this
|
||||
# point, so this is a plain terminal print, not something
|
||||
# the user could miss inside JOE's own UI.
|
||||
try:
|
||||
recovery_path = hd_core.save_offline_recovery(hd_root, note_id, client.document.text)
|
||||
recovery_msg = f"Your edits were saved to {recovery_path} instead."
|
||||
except Exception:
|
||||
logger.exception("Could not write offline recovery file for %s", note_id)
|
||||
recovery_msg = "Additionally, saving an offline recovery copy also failed -- see the log."
|
||||
print(
|
||||
f"\nhd-joe: {client.pending_count} edit(s) to '{note_id}' were "
|
||||
f"NOT saved to the server (connection issue?). {recovery_msg}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return rc
|
||||
finally:
|
||||
if proc and proc.poll() is None:
|
||||
proc.terminate()
|
||||
if agent:
|
||||
agent.stop.set()
|
||||
client.close()
|
||||
try: sock.unlink(missing_ok=True)
|
||||
except OSError: pass
|
||||
if tmp:
|
||||
try: tmp.unlink()
|
||||
except FileNotFoundError: pass
|
||||
|
||||
|
||||
if __name__=="__main__":
|
||||
raise SystemExit(main())
|
||||
110
hd-joe/joe_wrapper.py
Executable file
110
hd-joe/joe_wrapper.py
Executable file
@@ -0,0 +1,110 @@
|
||||
#!/usr/bin/env python3
|
||||
"""joe wrapper: routes to hd-joe when the target is (or would be) an
|
||||
hd-managed note, otherwise execs the real patched joe unmodified.
|
||||
|
||||
Installed AT the 'joe' name by install.sh (see install_joe() there) --
|
||||
NOT meant to be run directly under its own name during development; see
|
||||
decide() for the actual logic, which is what's unit-tested.
|
||||
|
||||
Two decisions, both explicit choices Joakim made, not guesses:
|
||||
1. If the argument resolves into an EXISTING hd-managed note (anywhere
|
||||
under some .hd/notes/), route to hd-joe -- regardless of cwd. This is
|
||||
the safety half: it stops `joe` from silently editing a note's cache
|
||||
file directly on disk, bypassing HedgeDoc entirely, just because you
|
||||
happened to open it by path from outside ~/notes.
|
||||
2. Else, if cwd itself is inside an hd-managed folder, treat a single
|
||||
bare name as `hd-joe <name>` -- creates the note if it doesn't exist
|
||||
yet, exactly like running hd-joe directly would.
|
||||
Anything else -- multiple files, flags, or cwd and argument both unrelated
|
||||
to any hd-managed folder -- goes straight to the real, unmodified joe.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
THIS_DIR = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(THIS_DIR.parent / "hd_common"))
|
||||
import hd_core # noqa: E402
|
||||
|
||||
DEFAULT_REAL_JOE = str(THIS_DIR.parent / "joe-patch" / "build" / "joe-4.8" / "joe" / "joe")
|
||||
HD_JOE_AGENT = str(THIS_DIR / "hd_joe_agent.py")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Decision:
|
||||
program: str # "real_joe" or "hd_joe"
|
||||
args: list[str] # argv to pass (not including the program name itself)
|
||||
|
||||
|
||||
def decide(argv: list[str], cwd: Path, real_joe_exists=None) -> Decision:
|
||||
"""Pure decision logic, no process launching -- so it's testable without
|
||||
actually exec-ing anything. `real_joe_exists` is injectable for tests;
|
||||
defaults to a real filesystem check.
|
||||
"""
|
||||
# Only try to be smart for "joe <one-thing>" with no flags. Multiple
|
||||
# files, -flags, or no args at all: always real joe, unmodified --
|
||||
# anything else risks second-guessing a normal joe invocation.
|
||||
positionals = [a for a in argv if not a.startswith("-")]
|
||||
if len(argv) != 1 or len(positionals) != 1:
|
||||
return Decision("real_joe", argv)
|
||||
|
||||
arg = argv[0]
|
||||
path = Path(arg)
|
||||
if not path.is_absolute():
|
||||
# Resolved against the passed-in `cwd`, not whatever the OS thinks
|
||||
# the real process cwd is -- makes this testable without actually
|
||||
# chdir-ing the test process, and in production `cwd` is always
|
||||
# Path.cwd() anyway, so behavior is identical there.
|
||||
path = cwd / path
|
||||
|
||||
# Case 1: the argument already resolves into an existing hd-managed
|
||||
# note, wherever we happen to be standing right now.
|
||||
if path.exists():
|
||||
resolved = path.resolve()
|
||||
notes_dir = resolved.parent
|
||||
hd_dir = notes_dir.parent
|
||||
if notes_dir.name == hd_core.NOTES_DIRNAME and hd_dir.name == ".hd" and resolved.suffix == ".md":
|
||||
hd_root = hd_dir.parent
|
||||
note_id = resolved.stem
|
||||
try:
|
||||
config = hd_core.Config.load(hd_dir)
|
||||
cookies = hd_core.Cookies.load(hd_dir)
|
||||
except (FileNotFoundError, KeyError, ValueError):
|
||||
# .hd/ exists but config/cookies are missing or unreadable --
|
||||
# don't fail the edit, just fall back to plain joe on the
|
||||
# cache file rather than crash on something hd-joe needs.
|
||||
return Decision("real_joe", argv)
|
||||
return Decision("hd_joe", [config.url, note_id, "--cookie", cookies.header])
|
||||
# An existing file that ISN'T an hd-managed note: always real joe --
|
||||
# never silently create-or-open it as if the path were a note name.
|
||||
return Decision("real_joe", argv)
|
||||
|
||||
# Case 2: the argument doesn't exist as a file yet. Only treat it as a
|
||||
# note name to create-or-open if we're standing inside an hd-managed
|
||||
# folder -- otherwise this is just "make me a new file", plain joe's
|
||||
# ordinary job.
|
||||
hd_root = hd_core.find_hd_root(cwd)
|
||||
if hd_root is not None:
|
||||
return Decision("hd_joe", [arg])
|
||||
|
||||
return Decision("real_joe", argv)
|
||||
|
||||
|
||||
def run(decision: Decision, real_joe_path: str = DEFAULT_REAL_JOE) -> None:
|
||||
if decision.program == "real_joe":
|
||||
os.execv(real_joe_path, [real_joe_path, *decision.args])
|
||||
else:
|
||||
os.execv(sys.executable, [sys.executable, HD_JOE_AGENT, *decision.args])
|
||||
|
||||
|
||||
def main() -> None:
|
||||
decision = decide(sys.argv[1:], Path.cwd())
|
||||
run(decision)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
3
hd-joe/requirements.txt
Normal file
3
hd-joe/requirements.txt
Normal file
@@ -0,0 +1,3 @@
|
||||
-r ../hd_common/requirements.txt
|
||||
werkzeug>=3.0 # tests only, not needed to run hd-joe itself
|
||||
pexpect>=4.9 # tests only (drives real JOE under a pty)
|
||||
106
hd-joe/test_disconnect_hook.py
Normal file
106
hd-joe/test_disconnect_hook.py
Normal file
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Direct test of HedgeDocClient.on_connection_state_changed -- the hook
|
||||
Agent.on_connection_state_changed (hd_joe_agent.py) subscribes to, to show
|
||||
the "OFFLINE"/"Back online" message in JOE. Tested against HedgeDocClient
|
||||
directly rather than through a full pty+JOE session: a controlled
|
||||
client.sio.disconnect() call is a reliable, immediate, genuine transport
|
||||
disconnect -- no dependency on how fast a killed server gets noticed.
|
||||
"""
|
||||
import socket as socketmod
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import socketio
|
||||
from werkzeug.serving import make_server
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common"))
|
||||
from hd_client import HedgeDocClient
|
||||
|
||||
PASS = []
|
||||
FAIL = []
|
||||
|
||||
|
||||
def check(name, cond, detail=""):
|
||||
if cond:
|
||||
PASS.append(name)
|
||||
else:
|
||||
FAIL.append((name, detail))
|
||||
print(f"FAIL: {name} {detail}")
|
||||
|
||||
|
||||
class MinimalFakeServer:
|
||||
def __init__(self, port):
|
||||
self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*")
|
||||
|
||||
@self.sio.event
|
||||
def connect(sid, environ, auth):
|
||||
self.sio.emit("doc", {"str": "hello", "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 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()
|
||||
server = MinimalFakeServer(port)
|
||||
server.start()
|
||||
time.sleep(0.2)
|
||||
|
||||
states = []
|
||||
client = HedgeDocClient(
|
||||
f"http://127.0.0.1:{port}", "n1",
|
||||
on_connection_state_changed=lambda connected: states.append(connected),
|
||||
)
|
||||
|
||||
try:
|
||||
client.connect()
|
||||
client.wait_ready(timeout=5)
|
||||
check("no state change recorded yet from connect() alone "
|
||||
"(the hook fires from the socketio 'connect' event, checked next)",
|
||||
True) # placeholder: the real assertion is the next block
|
||||
|
||||
# connect() itself should have triggered on_connection_state_changed(True)
|
||||
# via _on_connect -- give the event loop a moment, then check.
|
||||
time.sleep(0.2)
|
||||
check("on_connection_state_changed(True) fired after connect()",
|
||||
True in states, states)
|
||||
|
||||
states.clear()
|
||||
client.sio.disconnect()
|
||||
time.sleep(0.5)
|
||||
check("on_connection_state_changed(False) fired after an explicit disconnect",
|
||||
False in states, states)
|
||||
check("no True recorded after a disconnect with no reconnect attempted",
|
||||
True not in states, states)
|
||||
|
||||
finally:
|
||||
try:
|
||||
if client.sio.connected:
|
||||
client.sio.disconnect()
|
||||
except Exception:
|
||||
pass
|
||||
server.stop()
|
||||
|
||||
print(f"\n{len(PASS)} passed, {len(FAIL)} failed")
|
||||
return 0 if not FAIL else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
172
hd-joe/test_hd_cache_live_refresh.py
Normal file
172
hd-joe/test_hd_cache_live_refresh.py
Normal file
@@ -0,0 +1,172 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verifies the follow-up to the cache-refresh fix: while hd-joe is still
|
||||
open, an edit from ANOTHER client (webUI, in practice) should show up in
|
||||
the local .hd/notes/<id>.md cache within about a second -- not only once
|
||||
you quit. Throttled to at most once/second (see Agent.remote_operation),
|
||||
so this waits past that window before checking.
|
||||
"""
|
||||
import json
|
||||
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
|
||||
from werkzeug.wrappers import Request, Response
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common"))
|
||||
from hd_client import apply_operation
|
||||
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")
|
||||
|
||||
|
||||
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, port, initial_text):
|
||||
self.text = initial_text
|
||||
self.revision = 0
|
||||
self.lock = threading.Lock()
|
||||
|
||||
self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*")
|
||||
|
||||
@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:", 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():
|
||||
port = free_port()
|
||||
note_id = "n1"
|
||||
initial_content = "---\ntitle: Masten\ntags: sl6cv\n---\n\nstarting content"
|
||||
server = FakeServer(port, initial_content)
|
||||
server.start()
|
||||
time.sleep(0.2)
|
||||
|
||||
tmpdir = Path(tempfile.mkdtemp(prefix="hd-live-refresh-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-live-refresh.log"
|
||||
sock_path = "/tmp/hd-joe-live-refresh.sock"
|
||||
for p in (log_path, sock_path):
|
||||
try:
|
||||
os.remove(p)
|
||||
except OSError:
|
||||
pass
|
||||
cmd = f'python3 {AGENT} "Masten" --joe {JOE_BIN} --socket {sock_path} --log {log_path} --debug'
|
||||
child = pexpect.spawn(cmd, cwd=str(tag_dir), env={**os.environ, "TERM": "xterm"},
|
||||
dimensions=(24, 80), timeout=10)
|
||||
time.sleep(1.0) # let hd-joe connect and settle
|
||||
|
||||
cache_before = (hd_dir / "notes" / f"{note_id}.md").read_text()
|
||||
ok &= "starting content" in cache_before
|
||||
ok &= "REMOTE EDIT" not in cache_before
|
||||
print("cache before remote edit:", repr(cache_before[-40:]))
|
||||
|
||||
# A second connection -- standing in for webUI -- edits the SAME note
|
||||
# while hd-joe is still open.
|
||||
remote = socketio.Client()
|
||||
remote.connect(f"http://127.0.0.1:{port}/?noteId={note_id}", socketio_path="socket.io",
|
||||
transports=["websocket", "polling"])
|
||||
time.sleep(0.3)
|
||||
op = [len(initial_content), " -- REMOTE EDIT"]
|
||||
remote.emit("operation", (0, op, {"ranges": []}))
|
||||
time.sleep(1.5) # past the 1s throttle window
|
||||
|
||||
# Check the cache WHILE hd-joe is STILL RUNNING -- this is the point
|
||||
# of the test. Don't quit yet.
|
||||
cache_during = (hd_dir / "notes" / f"{note_id}.md").read_text()
|
||||
print("cache while hd-joe still open:", repr(cache_during[-40:]))
|
||||
ok &= "REMOTE EDIT" in cache_during
|
||||
|
||||
remote.disconnect()
|
||||
|
||||
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)
|
||||
|
||||
finally:
|
||||
if child and child.isalive():
|
||||
child.terminate(force=True)
|
||||
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())
|
||||
209
hd-joe/test_hd_cache_refresh.py
Normal file
209
hd-joe/test_hd_cache_refresh.py
Normal file
@@ -0,0 +1,209 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verifies the bug Joakim hit: after editing an EXISTING note through
|
||||
hd-joe and quitting, the local .hd/notes/<id>.md cache (and thus what
|
||||
`cat` on the symlink shows) must reflect the edit -- not just the server.
|
||||
"""
|
||||
import json
|
||||
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
|
||||
from werkzeug.wrappers import Request, Response
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common"))
|
||||
from hd_client import apply_operation
|
||||
from hd_core import Config, Cookies, State, content_hash, parse_current_tags, parse_frontmatter
|
||||
|
||||
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")
|
||||
|
||||
|
||||
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:
|
||||
def __init__(self, port, initial_notes):
|
||||
self.notes = initial_notes # id -> {"content", "time", "revision"}
|
||||
self.port = port
|
||||
self.lock = threading.Lock()
|
||||
|
||||
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 == "/history":
|
||||
with self.lock:
|
||||
history = []
|
||||
for nid, n in self.notes.items():
|
||||
fm = parse_frontmatter(n["content"])
|
||||
import yaml
|
||||
meta = yaml.safe_load(fm["yaml_str"]) or {} if fm else {}
|
||||
tags = parse_current_tags(meta)
|
||||
title = meta.get("title", 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 main():
|
||||
port = free_port()
|
||||
note_id = "n1"
|
||||
initial_content = "---\ntitle: Masten\ntags: sl6cv\n---\n\nold content here"
|
||||
server = CombinedFakeServer(port, {note_id: {"content": initial_content, "time": 1, "revision": 0}})
|
||||
server.start()
|
||||
time.sleep(0.2)
|
||||
|
||||
tmpdir = Path(tempfile.mkdtemp(prefix="hd-cache-refresh-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)
|
||||
|
||||
# Pre-populate state + cache as `hdc sync` would have, from an EARLIER sync
|
||||
# (deliberately stale -- "old content here" -- to prove the refresh works).
|
||||
from hd_core import NoteState
|
||||
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
|
||||
try:
|
||||
log_path = "/tmp/hd-joe-cache-refresh.log"
|
||||
sock_path = "/tmp/hd-joe-cache-refresh.sock"
|
||||
for p in (log_path, sock_path):
|
||||
try:
|
||||
os.remove(p)
|
||||
except OSError:
|
||||
pass
|
||||
cmd = f'python3 {AGENT} "Masten" --joe {JOE_BIN} --socket {sock_path} --log {log_path} --debug'
|
||||
child = pexpect.spawn(cmd, cwd=str(tag_dir), env={**os.environ, "TERM": "xterm"},
|
||||
dimensions=(24, 80), timeout=10)
|
||||
time.sleep(1.0)
|
||||
|
||||
# Go to EOF and type -- mirrors Joakim's actual test.
|
||||
child.send("\x0bv")
|
||||
time.sleep(0.3)
|
||||
child.send(" -- edited via hd-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)
|
||||
|
||||
server_text = server.notes[note_id]["content"]
|
||||
print("server content:", repr(server_text[-60:]))
|
||||
ok &= "edited via hd-joe" in server_text
|
||||
|
||||
cache_text = (hd_dir / "notes" / f"{note_id}.md").read_text()
|
||||
print("local cache content:", repr(cache_text[-60:]))
|
||||
ok &= cache_text == server_text
|
||||
# We typed at EOF, so the original text is still there as a prefix --
|
||||
# the bug this test guards against is the cache staying at the OLD
|
||||
# revision entirely, not the old text being removed.
|
||||
ok &= cache_text.startswith("---\ntitle: Masten")
|
||||
|
||||
symlink_text = (tag_dir / "Masten").read_text()
|
||||
ok &= symlink_text == server_text
|
||||
print("symlink (what 'cat' shows) matches server:", symlink_text == server_text)
|
||||
|
||||
reloaded_state = State.load(hd_dir)
|
||||
expected_hash = content_hash(server_text)
|
||||
hash_ok = reloaded_state.notes[note_id].content_hash == expected_hash
|
||||
print("state.json content_hash updated:", hash_ok)
|
||||
ok &= hash_ok
|
||||
|
||||
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())
|
||||
220
hd-joe/test_hd_create.py
Normal file
220
hd-joe/test_hd_create.py
Normal file
@@ -0,0 +1,220 @@
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent.parent / "hd_common"))
|
||||
from werkzeug.serving import make_server
|
||||
from werkzeug.wrappers import Request, Response
|
||||
|
||||
from hd_core import (
|
||||
NoteState, State, create_note, find_existing_symlink, find_hd_root,
|
||||
register_note, resolve_or_create_note, tag_from_cwd,
|
||||
)
|
||||
|
||||
PASS = []
|
||||
FAIL = []
|
||||
|
||||
|
||||
def check(name, cond, detail=""):
|
||||
if cond:
|
||||
PASS.append(name)
|
||||
else:
|
||||
FAIL.append((name, detail))
|
||||
print(f"FAIL: {name} {detail}")
|
||||
|
||||
|
||||
class FakeNewNoteServer:
|
||||
"""Just enough of HedgeDoc's POST /new to test create_note(): accept the
|
||||
body as the note's content, mint an id, redirect to /<id> -- mirrors
|
||||
lib/web/note/util.js's newNote() exactly (always redirects, id in
|
||||
Location, no JSON response)."""
|
||||
|
||||
def __init__(self, port):
|
||||
self.port = port
|
||||
self.notes = {}
|
||||
self._counter = 0
|
||||
self.last_content_type = None
|
||||
|
||||
def app(environ, start_response):
|
||||
request = Request(environ)
|
||||
if request.path == "/new" and request.method == "POST":
|
||||
self._counter += 1
|
||||
note_id = f"minted-{self._counter}"
|
||||
body = request.get_data(as_text=True)
|
||||
self.last_content_type = request.headers.get("Content-Type")
|
||||
self.notes[note_id] = body
|
||||
resp = Response(status=302, headers={"Location": f"/{note_id}"})
|
||||
return resp(environ, start_response)
|
||||
if request.path.endswith("/download"):
|
||||
nid = request.path.split("/")[1]
|
||||
resp = Response(self.notes.get(nid, ""), mimetype="text/markdown")
|
||||
return resp(environ, start_response)
|
||||
return Response("not found", status=404)(environ, start_response)
|
||||
|
||||
self.srv = make_server("127.0.0.1", port, 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():
|
||||
import socket
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
s.bind(("127.0.0.1", 0))
|
||||
p = s.getsockname()[1]
|
||||
s.close()
|
||||
return p
|
||||
|
||||
|
||||
def main():
|
||||
tmpdir = Path(tempfile.mkdtemp(prefix="hd-create-test-"))
|
||||
root = tmpdir / "notes"
|
||||
(root / ".hd" / "notes").mkdir(parents=True)
|
||||
|
||||
try:
|
||||
# --- find_hd_root: climbs up, git-style ---
|
||||
# Use a directory OUTSIDE the tag dirs for the climbing test, so the
|
||||
# temporary nesting doesn't make 'radio' itself look broken to the
|
||||
# freshness check that later tests depend on.
|
||||
deep = root / "climbtest" / "sub"
|
||||
deep.mkdir(parents=True)
|
||||
check("finds root from a nested cwd", find_hd_root(deep) == root.resolve())
|
||||
check("finds root from root itself", find_hd_root(root) == root.resolve())
|
||||
outside = tmpdir / "elsewhere"
|
||||
outside.mkdir()
|
||||
check("returns None with no .hd anywhere above", find_hd_root(outside) is None)
|
||||
|
||||
# --- tag_from_cwd ---
|
||||
(root / "radio").mkdir(exist_ok=True)
|
||||
check("root itself -> untagged, no error", tag_from_cwd(root, root) == (None, None))
|
||||
tag, err = tag_from_cwd(root, root / "radio")
|
||||
check("one level -> that tag, no error", tag == "radio" and err is None, (tag, err))
|
||||
tag2, err2 = tag_from_cwd(root, root / "climbtest" / "sub")
|
||||
check("two levels -> error, not a compound tag", tag2 is None and err2 is not None, (tag2, err2))
|
||||
check("nesting error names the offending path", "nested" in err2 and "climbtest" in err2, err2)
|
||||
tag3, err3 = tag_from_cwd(root, root / ".hd")
|
||||
check("inside .hd -> refused", tag3 is None and err3 is not None, (tag3, err3))
|
||||
outside_tag, outside_err = tag_from_cwd(root, outside)
|
||||
check("outside root entirely -> error", outside_tag is None and outside_err is not None)
|
||||
|
||||
# --- create_note against a fake /new ---
|
||||
port = free_port()
|
||||
server = FakeNewNoteServer(port)
|
||||
server.start()
|
||||
time.sleep(0.2)
|
||||
|
||||
note_id, initial_text = create_note(f"http://127.0.0.1:{port}", "session=1", "My New Note", ["radio"])
|
||||
check("create_note returns the minted id", note_id == "minted-1", note_id)
|
||||
check("initial content has a frontmatter block", initial_text.startswith("---\n"), initial_text)
|
||||
check("initial content has the right title", "title: My New Note" in initial_text, initial_text)
|
||||
check("initial content has the right tag", "tags: radio" in initial_text, initial_text)
|
||||
check("server actually received that content", server.notes["minted-1"] == initial_text)
|
||||
|
||||
note_id2, text2 = create_note(f"http://127.0.0.1:{port}", "session=1", "Untagged Note", [])
|
||||
check("untagged create_note has no tags line", "tags:" not in text2, text2)
|
||||
|
||||
# --- register_note: local cache + symlink, no network ---
|
||||
state = State()
|
||||
ns = register_note(root, state, note_id, "My New Note", ["radio"], initial_text)
|
||||
check("register_note returns matching NoteState", ns.title == "My New Note" and ns.tags == ["radio"])
|
||||
check("cache file written", (root / ".hd" / "notes" / f"{note_id}.md").read_text() == initial_text)
|
||||
check("symlink created in the right tag dir", (root / "radio" / "My New Note").is_symlink())
|
||||
check("state updated in-memory", note_id in state.notes)
|
||||
|
||||
# --- find_existing_symlink ---
|
||||
found = find_existing_symlink(root, "radio", "My New Note")
|
||||
check("find_existing_symlink finds the one we just made", found == note_id, found)
|
||||
check("find_existing_symlink returns None for a name that isn't there",
|
||||
find_existing_symlink(root, "radio", "Nope") is None)
|
||||
check("find_existing_symlink returns None for the wrong tag",
|
||||
find_existing_symlink(root, "personal", "My New Note") is None)
|
||||
|
||||
server.stop()
|
||||
|
||||
# --- resolve_or_create_note: full flow, open-vs-create ---
|
||||
port2 = free_port()
|
||||
server2 = FakeNewNoteServer(port2)
|
||||
server2.start()
|
||||
time.sleep(0.2)
|
||||
url2 = f"http://127.0.0.1:{port2}"
|
||||
|
||||
radio_dir = root / "radio"
|
||||
note_id_a, created_a = resolve_or_create_note(root, radio_dir, "Fresh Project", url2, "session=1")
|
||||
check("first call creates a new note", created_a is True)
|
||||
check("new symlink exists after creation", (radio_dir / "Fresh Project").is_symlink())
|
||||
|
||||
note_id_b, created_b = resolve_or_create_note(root, radio_dir, "Fresh Project", url2, "session=1")
|
||||
check("second call with the same name opens, doesn't create", created_b is False)
|
||||
check("second call resolves to the SAME note id", note_id_b == note_id_a, (note_id_a, note_id_b))
|
||||
check("only one POST /new happened on the server", len(server2.notes) == 1, server2.notes)
|
||||
|
||||
# --- resolve_or_create_note refuses in a too-deep directory ---
|
||||
too_deep = root / "climbtest" / "sub"
|
||||
try:
|
||||
resolve_or_create_note(root, too_deep, "Whatever", url2, "session=1")
|
||||
check("refuses to create in a nested directory", False, "did not raise")
|
||||
except ValueError as exc:
|
||||
check("refuses to create in a nested directory", True)
|
||||
check("refusal message explains why", "nested" in str(exc), str(exc))
|
||||
|
||||
# --- the fresh target-directory check gates CREATION specifically ---
|
||||
broken_dir = root / "brokentag"
|
||||
(broken_dir / "accidental_subdir").mkdir(parents=True)
|
||||
try:
|
||||
resolve_or_create_note(root, broken_dir, "Should Not Exist", url2, "session=1")
|
||||
check("refuses to create in a directory containing a subdirectory", False, "did not raise")
|
||||
except ValueError as exc:
|
||||
check("refuses to create in a directory containing a subdirectory", True)
|
||||
check("refusal names the offending subdirectory",
|
||||
"accidental_subdir" in str(exc), str(exc))
|
||||
check("nothing was created on the server by the refused call",
|
||||
len(server2.notes) == 1, server2.notes)
|
||||
|
||||
# ...but OPENING an existing note in that same messy directory still works,
|
||||
# since that adds nothing new to an already-unreconcilable directory.
|
||||
note_id_c, created_c = resolve_or_create_note(root, radio_dir, "Openable", url2, "session=1")
|
||||
(broken_dir / "Openable").symlink_to(
|
||||
os.path.relpath(root / ".hd" / "notes" / f"{note_id_c}.md", broken_dir))
|
||||
note_id_d, created_d = resolve_or_create_note(root, broken_dir, "Openable", url2, "session=1")
|
||||
check("opening an existing note in a messy directory is still allowed",
|
||||
created_d is False and note_id_d == note_id_c, (note_id_c, note_id_d, created_d))
|
||||
|
||||
server2.stop()
|
||||
|
||||
# --- 'Name.md' resolves to the SAME note as 'Name' (the bug Joakim hit) ---
|
||||
port4 = free_port()
|
||||
server4 = FakeNewNoteServer(port4)
|
||||
server4.start()
|
||||
time.sleep(0.2)
|
||||
url4 = f"http://127.0.0.1:{port4}"
|
||||
radio_dir2 = root / "radio2"
|
||||
radio_dir2.mkdir(parents=True)
|
||||
|
||||
id_by_name, created_by_name = resolve_or_create_note(root, radio_dir2, "Masten", url4, "session=1")
|
||||
check("'Masten' creates a note", created_by_name is True)
|
||||
id_by_md, created_by_md = resolve_or_create_note(root, radio_dir2, "Masten.md", url4, "session=1")
|
||||
check("'Masten.md' opens the SAME note 'Masten' created, doesn't create a second",
|
||||
created_by_md is False and id_by_md == id_by_name, (id_by_name, id_by_md, created_by_md))
|
||||
check("only one POST /new happened despite two different spellings",
|
||||
len(server4.notes) == 1, server4.notes)
|
||||
server4.stop()
|
||||
|
||||
finally:
|
||||
shutil.rmtree(tmpdir, ignore_errors=True)
|
||||
|
||||
print(f"\n{len(PASS)} passed, {len(FAIL)} failed")
|
||||
return 0 if not FAIL else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
223
hd-joe/test_hd_joe_create.py
Normal file
223
hd-joe/test_hd_joe_create.py
Normal file
@@ -0,0 +1,223 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verifies `hd-joe <name>` 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 <name>` (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())
|
||||
114
hd-joe/test_joe_wrapper.py
Normal file
114
hd-joe/test_joe_wrapper.py
Normal file
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Tests joe_wrapper.decide() -- pure decision logic, no process launching --
|
||||
against both of Joakim's stated rules:
|
||||
1. An existing hd-managed note routes to hd-joe regardless of cwd.
|
||||
2. A not-yet-existing name routes to hd-joe's create-or-open ONLY when
|
||||
cwd itself is inside an hd-managed folder.
|
||||
"""
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common"))
|
||||
from hd_core import Config, Cookies
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from joe_wrapper import decide
|
||||
|
||||
PASS = []
|
||||
FAIL = []
|
||||
|
||||
|
||||
def check(name, cond, detail=""):
|
||||
if cond:
|
||||
PASS.append(name)
|
||||
else:
|
||||
FAIL.append((name, detail))
|
||||
print(f"FAIL: {name} {detail}")
|
||||
|
||||
|
||||
def main():
|
||||
tmpdir = Path(tempfile.mkdtemp(prefix="joe-wrapper-test-"))
|
||||
root = tmpdir / "notes"
|
||||
hd_dir = root / ".hd"
|
||||
(hd_dir / "notes").mkdir(parents=True)
|
||||
Config(url="https://hedgedoc.example", email=None).save(hd_dir)
|
||||
Cookies(header="session=abc").save(hd_dir)
|
||||
|
||||
note_id = "n1"
|
||||
(hd_dir / "notes" / f"{note_id}.md").write_text("---\ntitle: Masten\n---\n\nbody")
|
||||
tag_dir = root / "sl6cv"
|
||||
tag_dir.mkdir(parents=True)
|
||||
(tag_dir / "Masten").symlink_to(Path("..") / ".hd" / "notes" / f"{note_id}.md")
|
||||
|
||||
elsewhere = tmpdir / "elsewhere"
|
||||
elsewhere.mkdir()
|
||||
|
||||
unrelated_file = elsewhere / "scratch.txt"
|
||||
unrelated_file.write_text("just a normal file")
|
||||
|
||||
try:
|
||||
# --- Rule 1: an existing hd-managed note routes to hd-joe, from ANY cwd ---
|
||||
d = decide(["Masten"], cwd=tag_dir)
|
||||
check("existing note, cwd=tag dir -> hd_joe", d.program == "hd_joe", d)
|
||||
check("existing note -> correct url", d.args[0] == "https://hedgedoc.example", d)
|
||||
check("existing note -> correct note id", d.args[1] == note_id, d)
|
||||
check("existing note -> cookie passed explicitly (cwd-based discovery won't help elsewhere)",
|
||||
"--cookie" in d.args and "session=abc" in d.args, d)
|
||||
|
||||
d2 = decide([str(tag_dir / "Masten")], cwd=elsewhere)
|
||||
check("existing note opened by FULL PATH from an unrelated cwd -> still hd_joe",
|
||||
d2.program == "hd_joe", d2)
|
||||
check("full-path case -> same note id", d2.args[1] == note_id, d2)
|
||||
|
||||
d3 = decide([str(tag_dir / "Masten")], cwd=Path("/"))
|
||||
check("existing note opened from filesystem root -> still hd_joe", d3.program == "hd_joe", d3)
|
||||
|
||||
# --- Rule 2: a NOT-YET-EXISTING name -> hd_joe only if cwd is hd-managed ---
|
||||
d4 = decide(["Brand New Note"], cwd=tag_dir)
|
||||
check("new name, cwd IS hd-managed -> hd_joe (create-or-open)", d4.program == "hd_joe", d4)
|
||||
check("new name -> just the bare name passed through", d4.args == ["Brand New Note"], d4)
|
||||
|
||||
d5 = decide(["Brand New Note"], cwd=elsewhere)
|
||||
check("new name, cwd NOT hd-managed -> real_joe (plain new file)", d5.program == "real_joe", d5)
|
||||
check("real_joe case preserves the original arg", d5.args == ["Brand New Note"], d5)
|
||||
|
||||
# --- An existing file that's a normal, non-hd file -> always real joe ---
|
||||
d6 = decide([str(unrelated_file)], cwd=elsewhere)
|
||||
check("existing unrelated file -> real_joe, never treated as a note", d6.program == "real_joe", d6)
|
||||
|
||||
d7 = decide([str(unrelated_file)], cwd=tag_dir) # even from inside an hd-managed cwd
|
||||
check("existing unrelated file, cwd IS hd-managed -> still real_joe (it's not an hd note)",
|
||||
d7.program == "real_joe", d7)
|
||||
|
||||
# --- Multiple args, or any flag present -> always real joe, untouched ---
|
||||
d8 = decide(["fileA", "fileB"], cwd=tag_dir)
|
||||
check("two files -> real_joe untouched", d8.program == "real_joe" and d8.args == ["fileA", "fileB"], d8)
|
||||
|
||||
d9 = decide(["-wordwrap", "Masten"], cwd=tag_dir)
|
||||
check("a flag present -> real_joe untouched, no second-guessing",
|
||||
d9.program == "real_joe" and d9.args == ["-wordwrap", "Masten"], d9)
|
||||
|
||||
d10 = decide([], cwd=tag_dir)
|
||||
check("no args at all -> real_joe untouched", d10.program == "real_joe" and d10.args == [], d10)
|
||||
|
||||
# --- A dangling symlink pointing INTO .hd/notes/ at a nonexistent id:
|
||||
# path.exists() is False for a broken symlink -- falls through to
|
||||
# rule 2's "doesn't exist yet" branch, not treated as note 1. ---
|
||||
(tag_dir / "Broken").symlink_to(hd_dir / "notes" / "ghost.md")
|
||||
d11 = decide(["Broken"], cwd=tag_dir)
|
||||
check("broken symlink into .hd/notes/ -- cwd is hd-managed, so still hd_joe (create-or-open)",
|
||||
d11.program == "hd_joe", d11)
|
||||
check("broken-symlink case treats it as a plain name, not a resolved note",
|
||||
d11.args == ["Broken"], d11)
|
||||
|
||||
finally:
|
||||
shutil.rmtree(tmpdir, ignore_errors=True)
|
||||
|
||||
print(f"\n{len(PASS)} passed, {len(FAIL)} failed")
|
||||
return 0 if not FAIL else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
64
hd-joe/test_joe_wrapper_exec.py
Normal file
64
hd-joe/test_joe_wrapper_exec.py
Normal file
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Confirms joe_wrapper.py's os.execv actually works, not just decide()'s
|
||||
pure logic: point it at a plain, non-hd-managed file and verify real JOE
|
||||
opens it, edits happen, and the save on disk is a normal, ordinary local
|
||||
save -- no HedgeDoc connection attempted at all for this case.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pexpect
|
||||
|
||||
JOE_BIN = os.environ.get("JOE_BIN", "/home/claude/work/repo/joe-patch/build/joe-4.8/joe/joe")
|
||||
WRAPPER = str(Path(__file__).resolve().parent / "joe_wrapper.py")
|
||||
|
||||
|
||||
def main():
|
||||
tmpdir = Path(tempfile.mkdtemp(prefix="joe-wrapper-exec-test-"))
|
||||
scratch = tmpdir / "scratch.txt"
|
||||
scratch.write_text("original content\n")
|
||||
|
||||
ok = True
|
||||
try:
|
||||
# joe_wrapper.py's DEFAULT_REAL_JOE computes the same build path as
|
||||
# JOE_BIN's default above; run the wrapper directly, exactly as the
|
||||
# generated install.sh wrapper would exec it via the venv's python3.
|
||||
env = {**os.environ, "TERM": "xterm"}
|
||||
cmd = f"python3 {WRAPPER} {scratch}"
|
||||
child = pexpect.spawn(cmd, cwd=str(tmpdir), env=env, dimensions=(24, 80), timeout=10)
|
||||
time.sleep(0.8)
|
||||
|
||||
child.send("\x0bv") # Ctrl-K V: go to EOF
|
||||
time.sleep(0.3)
|
||||
child.send("added by real joe via the wrapper")
|
||||
time.sleep(0.4)
|
||||
|
||||
child.send("\x0bx") # Ctrl-K X: save and exit
|
||||
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)
|
||||
|
||||
final = scratch.read_text()
|
||||
print("final file content:", repr(final))
|
||||
ok &= "original content" in final
|
||||
ok &= "added by real joe via the wrapper" in final
|
||||
|
||||
finally:
|
||||
import shutil
|
||||
shutil.rmtree(tmpdir, ignore_errors=True)
|
||||
|
||||
print("\nPASS" if ok else "\nFAIL")
|
||||
return 0 if ok else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
159
hd-joe/test_joe_wrapper_hdjoe_exec.py
Normal file
159
hd-joe/test_joe_wrapper_hdjoe_exec.py
Normal file
@@ -0,0 +1,159 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Confirms joe_wrapper.py's os.execv into hd_joe_agent.py actually works
|
||||
for an existing hd-managed note (Rule 1) -- not just decide()'s pure
|
||||
logic. Opens a note by its bare symlink name from INSIDE the tag dir
|
||||
(the common case), edits, and checks the server received it live.
|
||||
"""
|
||||
import json
|
||||
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_client import apply_operation
|
||||
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")
|
||||
WRAPPER = str(Path(__file__).resolve().parent / "joe_wrapper.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, port, initial_text):
|
||||
self.text = initial_text
|
||||
self.revision = 0
|
||||
self.lock = threading.Lock()
|
||||
|
||||
self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*")
|
||||
|
||||
@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:", exc, operation)
|
||||
return
|
||||
self.revision += 1
|
||||
self.sio.emit("ack", self.revision, 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 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\nstarting content"
|
||||
server = FakeServer(port, initial_content)
|
||||
server.start()
|
||||
time.sleep(0.2)
|
||||
|
||||
tmpdir = Path(tempfile.mkdtemp(prefix="joe-wrapper-hdjoe-exec-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/joe-wrapper-hdjoe-exec.log"
|
||||
try:
|
||||
os.remove(log_path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# Invoke exactly like real joe would be invoked -- through the
|
||||
# wrapper, with just the bare symlink NAME (not a resolved path),
|
||||
# from inside the tag directory. This is Rule 1's "existing note"
|
||||
# case reached via a relative name, the way someone actually types
|
||||
# `joe Masten` day to day, not `joe /full/path/to/Masten`.
|
||||
cmd = f"python3 {WRAPPER} Masten"
|
||||
child = pexpect.spawn(cmd, cwd=str(tag_dir), env={**os.environ, "TERM": "xterm"},
|
||||
dimensions=(24, 80), timeout=10)
|
||||
time.sleep(1.0)
|
||||
|
||||
child.send("\x0bv") # Ctrl-K V: EOF
|
||||
time.sleep(0.3)
|
||||
child.send(" -- via joe wrapper")
|
||||
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)
|
||||
|
||||
print("server text:", repr(server.text[-50:]))
|
||||
ok &= "via joe wrapper" in server.text
|
||||
ok &= server.revision > 0
|
||||
|
||||
finally:
|
||||
if child and child.isalive():
|
||||
child.terminate(force=True)
|
||||
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())
|
||||
248
hd-joe/test_offline_handling.py
Normal file
248
hd-joe/test_offline_handling.py
Normal file
@@ -0,0 +1,248 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The scenario Joakim reported: edit a note, go offline mid-session, keep
|
||||
typing, quit. Simulates "offline" by having the fake server keep the
|
||||
connection open but stop acking anything (StoppableFakeServer.go_silent) --
|
||||
tried an actual server shutdown() first; python-socketio's client doesn't
|
||||
reliably notice an already-established websocket has gone away within a
|
||||
short test timeout, since shutdown() stops accepting new connections
|
||||
without necessarily tearing down ones already open. Withholding acks is
|
||||
deterministic and exercises exactly what matters here (drain_pending()'s
|
||||
timeout and everything downstream of it), even though it doesn't exercise
|
||||
actual transport-level disconnect detection -- see test_disconnect_hook.py
|
||||
for that, tested directly against HedgeDocClient rather than through a
|
||||
full pty+JOE session.
|
||||
|
||||
Verifies:
|
||||
- the tracked cache (.hd/notes/<id>.md) is NOT overwritten with the
|
||||
unacknowledged offline text (the false-sync/poisoning bug)
|
||||
- the offline text is NOT just lost -- a recovery file under
|
||||
.hd/offline-recovery/ contains it
|
||||
- a clear warning is printed to the terminal after JOE exits
|
||||
"""
|
||||
import glob
|
||||
import json
|
||||
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_client import apply_operation
|
||||
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")
|
||||
|
||||
|
||||
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 StoppableFakeServer:
|
||||
"""`go_silent` deterministically simulates "offline" from the CLIENT's
|
||||
point of view without depending on how fast (if at all) a graceful
|
||||
werkzeug shutdown() actually severs an already-established websocket --
|
||||
tried that first; it's not reliable within a short test timeout, since
|
||||
shutdown() stops accepting new work without necessarily tearing down
|
||||
connections already open. Withholding acks is deterministic: the
|
||||
connection stays technically up, but nothing the client sends after
|
||||
go_silent is True ever gets acknowledged -- exactly what matters for
|
||||
drain_pending()'s timeout and everything downstream of it.
|
||||
"""
|
||||
|
||||
def __init__(self, port, initial_text):
|
||||
self.text = initial_text
|
||||
self.revision = 0
|
||||
self.lock = threading.Lock()
|
||||
self.go_silent = False
|
||||
self.silently_received = []
|
||||
|
||||
self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*")
|
||||
|
||||
@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 self.go_silent:
|
||||
self.silently_received.append(operation)
|
||||
return # accepted at the transport level, never acked
|
||||
if base_revision != self.revision:
|
||||
return
|
||||
try:
|
||||
self.text = apply_operation_strict(self.text, operation)
|
||||
except Exception as exc:
|
||||
print("[fake server] rejected:", exc, operation)
|
||||
return
|
||||
self.revision += 1
|
||||
self.sio.emit("ack", self.revision, 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 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\nonline content"
|
||||
server = StoppableFakeServer(port, initial_content)
|
||||
server.start()
|
||||
time.sleep(0.2)
|
||||
|
||||
tmpdir = Path(tempfile.mkdtemp(prefix="hd-offline-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-offline-test.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)
|
||||
|
||||
# --- while online: type something, confirm it reaches the server ---
|
||||
child.send("\x0bv") # EOF
|
||||
time.sleep(0.3)
|
||||
child.send(" online-edit")
|
||||
time.sleep(0.6)
|
||||
check1 = "online-edit" in server.text
|
||||
print("online edit reached server:", check1)
|
||||
ok &= check1
|
||||
|
||||
# --- go "offline": the server keeps accepting the connection but
|
||||
# stops acking anything from here on -- see StoppableFakeServer's
|
||||
# docstring for why this, not an actual server shutdown, is the
|
||||
# reliable way to simulate it in a test ---
|
||||
server.go_silent = True
|
||||
|
||||
# --- keep typing -- this is the part that used to silently vanish ---
|
||||
child.send(" OFFLINE-TEXT-SHOULD-BE-RECOVERED")
|
||||
time.sleep(0.8)
|
||||
|
||||
# --- quit ---
|
||||
child.send("\x0bx")
|
||||
time.sleep(0.4)
|
||||
child.send("\r")
|
||||
try:
|
||||
# expect(EOF), not wait(): we need pexpect to actually READ and
|
||||
# buffer everything printed up to process exit (including the
|
||||
# plain print()s the agent makes after JOE's own curses UI has
|
||||
# torn down) so it ends up in .before -- wait() alone just
|
||||
# blocks for the exit code without reading any output at all.
|
||||
child.expect(pexpect.EOF, timeout=10)
|
||||
except pexpect.TIMEOUT:
|
||||
pass
|
||||
pty_output = child.before.decode("utf-8", errors="replace") if child.before else ""
|
||||
if child.isalive():
|
||||
child.terminate(force=True)
|
||||
time.sleep(0.3)
|
||||
|
||||
# --- the tracked cache must NOT contain the offline text ---
|
||||
cache_text = (hd_dir / "notes" / f"{note_id}.md").read_text()
|
||||
check2 = "OFFLINE-TEXT-SHOULD-BE-RECOVERED" not in cache_text
|
||||
print("tracked cache does NOT contain offline text (not poisoned):", check2, repr(cache_text[-40:]))
|
||||
ok &= check2
|
||||
# NOT "still has the online edit": update_note_cache() is currently
|
||||
# all-or-nothing -- any unacked pending operation (even one that
|
||||
# arrived after other, already-acked edits in the same session)
|
||||
# blocks the cache update entirely, so the cache stays at whatever
|
||||
# the last fully successful sync left it at. Safe (never poisons),
|
||||
# just not maximally granular -- a possible future refinement would
|
||||
# track acked-vs-optimistic text separately and cache the acked
|
||||
# portion. Asserting the ACTUAL current (conservative) behavior here.
|
||||
check3 = cache_text == initial_content
|
||||
print("tracked cache unchanged from before this session (conservative, not poisoned):", check3)
|
||||
ok &= check3
|
||||
|
||||
# --- state.json's hash must still match the (unpoisoned) cache file ---
|
||||
reloaded = State.load(hd_dir)
|
||||
check4 = reloaded.notes[note_id].content_hash == content_hash(cache_text)
|
||||
print("state.json hash matches the actual (unpoisoned) cache file:", check4)
|
||||
ok &= check4
|
||||
|
||||
# --- a recovery file must exist, containing the offline text ---
|
||||
recovery_files = sorted(glob.glob(str(hd_dir / "offline-recovery" / f"{note_id}-*.md")))
|
||||
check5 = len(recovery_files) == 1
|
||||
print("exactly one recovery file found:", check5, recovery_files)
|
||||
ok &= check5
|
||||
if recovery_files:
|
||||
recovery_text = Path(recovery_files[0]).read_text()
|
||||
check6 = "OFFLINE-TEXT-SHOULD-BE-RECOVERED" in recovery_text
|
||||
print("recovery file contains the offline text:", check6)
|
||||
ok &= check6
|
||||
|
||||
# --- a clear warning was printed to the terminal after JOE exited ---
|
||||
check7 = "NOT saved to the server" in pty_output and "recovery" in pty_output.lower()
|
||||
print("terminal warning printed after quit:", check7)
|
||||
if not check7:
|
||||
print("--- captured output tail ---")
|
||||
print(pty_output[-800:])
|
||||
ok &= check7
|
||||
|
||||
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())
|
||||
160
hd-joe/test_real_disconnect_pty.py
Normal file
160
hd-joe/test_real_disconnect_pty.py
Normal 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())
|
||||
75
hd-joe/test_shadow_text_sync.py
Normal file
75
hd-joe/test_shadow_text_sync.py
Normal file
@@ -0,0 +1,75 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Unit test for a bug found while tracing through the offline scenario:
|
||||
Agent.handle_local() used to only update self._shadow_text on the success
|
||||
path. But send_operation() (hd_client.py) already updates
|
||||
client.document.text optimistically BEFORE attempting to send -- so when
|
||||
sending raises (offline, or any other reason), document.text has already
|
||||
moved but _shadow_text hadn't, until this was moved into a `finally`.
|
||||
Left unfixed, the NEXT remote operation would get translated into JOE IPC
|
||||
commands against a stale baseline -- a buffer-corruption risk, not just a
|
||||
lost-edit one.
|
||||
|
||||
No real client/server needed: a minimal fake client that reproduces
|
||||
exactly the one behavior this test cares about (document.text updates,
|
||||
THEN the call raises) is enough, and keeps this fast and deterministic.
|
||||
"""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common"))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import hd_joe_agent
|
||||
|
||||
PASS = []
|
||||
FAIL = []
|
||||
|
||||
|
||||
def check(name, cond, detail=""):
|
||||
if cond:
|
||||
PASS.append(name)
|
||||
else:
|
||||
FAIL.append((name, detail))
|
||||
print(f"FAIL: {name} {detail}")
|
||||
|
||||
|
||||
class FakeClient:
|
||||
"""Reproduces hd_client.HedgeDocClient.send_operation()'s real behavior
|
||||
just enough for this test: document.text updates optimistically, THEN
|
||||
the call raises -- exactly the order that made _shadow_text go stale."""
|
||||
|
||||
def __init__(self, text):
|
||||
self.document = SimpleNamespace(text=text)
|
||||
self.on_remote_operation_detail = None
|
||||
self.on_connection_state_changed = None
|
||||
|
||||
def insert(self, cp, inserted):
|
||||
t = self.document.text
|
||||
self.document.text = t[:cp] + inserted + t[cp:]
|
||||
raise ConnectionError("simulated: send failed after the local buffer already moved")
|
||||
|
||||
def send_operation(self, op):
|
||||
raise ConnectionError("simulated: send failed")
|
||||
|
||||
|
||||
def main():
|
||||
client = FakeClient("hello world")
|
||||
agent = hd_joe_agent.Agent(client, sock_path=Path("/tmp/unused.sock"), buffer_path=Path("/tmp/unused.md"))
|
||||
|
||||
# "hi " inserted at position 0 -> "hi hello world", hex-encoded per the
|
||||
# real wire format JOE -> agent uses.
|
||||
hexpayload = "hi ".encode("utf-8").hex()
|
||||
agent.handle_local(f"I 0 {hexpayload}")
|
||||
|
||||
check("the fake client's optimistic insert happened despite the raise",
|
||||
client.document.text == "hi hello world", client.document.text)
|
||||
check("_shadow_text was updated to match, via the finally block, even though insert() raised",
|
||||
getattr(agent, "_shadow_text", None) == client.document.text,
|
||||
(getattr(agent, "_shadow_text", None), client.document.text))
|
||||
|
||||
print(f"\n{len(PASS)} passed, {len(FAIL)} failed")
|
||||
return 0 if not FAIL else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user