#!/usr/bin/env python3 """PicoCalc HedgeDoc client 0.5.4. HedgeDoc transport + text OT client. 0.5 adds a real local operation queue and pairwise operational transformation for concurrent edits. Wire format confirmed for HedgeDoc 1.x: client -> server: operation(base_revision, operation, selection) server -> sender: ack(new_revision) server -> peers: operation(client_id, new_revision, operation, selection, id) """ from __future__ import annotations import logging import threading from urllib.request import Request, urlopen from urllib.parse import quote from dataclasses import dataclass, field from typing import Any, Callable, Optional import socketio logger = logging.getLogger("picocalc.hd") Operation = list[Any] def normalize_operation(op: Any) -> Operation: if not isinstance(op, list): raise TypeError(f"operation must be a list, got {type(op).__name__}") return op def utf16_len(text: str) -> int: """Return JavaScript/CodeMirror string length (UTF-16 code units).""" return len(text.encode("utf-16-le")) // 2 def utf16_to_char_index(text: str, units: int) -> int: """Convert a UTF-16 code-unit offset to a Python character index.""" if units < 0: raise ValueError("negative UTF-16 offset") total = utf16_len(text) if units > total: raise ValueError(f"UTF-16 offset {units} exceeds document length {total}") if units == 0: return 0 raw = text.encode("utf-16-le") cut = units * 2 try: prefix = raw[:cut].decode("utf-16-le") except UnicodeDecodeError as exc: raise ValueError(f"UTF-16 offset {units} splits a surrogate pair") from exc return len(prefix) def apply_operation(text: str, op: Operation) -> str: """Apply HedgeDoc/ot.js operations, whose lengths are UTF-16 units.""" result: list[str] = [] pos_units = 0 doc_units = utf16_len(text) for component in normalize_operation(op): if isinstance(component, bool): raise TypeError(f"unsupported operation component: {component!r}") if isinstance(component, int): if component >= 0: end_units = pos_units + component if end_units > doc_units: raise ValueError(f"retain {component} exceeds document length") a = utf16_to_char_index(text, pos_units) b = utf16_to_char_index(text, end_units) result.append(text[a:b]) pos_units = end_units else: count = -component end_units = pos_units + count if end_units > doc_units: raise ValueError(f"delete {count} exceeds document length") utf16_to_char_index(text, end_units) pos_units = end_units elif isinstance(component, str): result.append(component) else: raise TypeError(f"unsupported operation component: {component!r}") if pos_units != doc_units: raise ValueError( f"operation did not consume document: consumed {pos_units}, len={doc_units}" ) return "".join(result) def _op_length(component: Any) -> int: if isinstance(component, bool): raise TypeError("bool is not a valid OT component") if isinstance(component, int): return abs(component) if isinstance(component, str): return utf16_len(component) raise TypeError(f"unsupported operation component: {component!r}") def _append_component(out: Operation, component: Any) -> None: if component == 0 or component == "": return if isinstance(component, int) and out and isinstance(out[-1], int): # Retains and deletes must never merge with each other. if (component >= 0) == (out[-1] >= 0): out[-1] += component return if isinstance(component, str) and out and isinstance(out[-1], str): out[-1] += component return out.append(component) class _OpIter: def __init__(self, op: Operation): self.components = list(op) self.index = 0 self.offset = 0 def done(self) -> bool: return self.index >= len(self.components) def component(self) -> Any: if self.done(): raise IndexError("operation exhausted") return self.components[self.index] def remaining(self) -> int: return _op_length(self.component()) - self.offset def take(self, n: int) -> Any: if n <= 0 or self.done(): raise ValueError("invalid OT iterator take") c = self.component() start = self.offset end = start + n if isinstance(c, int): if c >= 0: piece: Any = n else: piece = -n else: piece = c[start:end] self.offset = end if self.offset == _op_length(c): self.index += 1 self.offset = 0 return piece def transform_operations(a: Operation, b: Operation) -> tuple[Operation, Operation]: """Transform two concurrent text operations. Returns (a', b') where: apply(apply(S, a), b') == apply(apply(S, b), a') Same-position inserts are ordered deterministically in favour of ``a``. This matches the usual ot.js-style left/right tie-break behaviour and is enough for convergence between clients using the same transform. """ ia = _OpIter(normalize_operation(a)) ib = _OpIter(normalize_operation(b)) ap: Operation = [] bp: Operation = [] while not ia.done() or not ib.done(): if not ia.done() and isinstance(ia.component(), str): s = ia.take(ia.remaining()) _append_component(ap, s) _append_component(bp, len(s)) continue if not ib.done() and isinstance(ib.component(), str): s = ib.take(ib.remaining()) _append_component(ap, len(s)) _append_component(bp, s) continue if ia.done() or ib.done(): raise ValueError("concurrent operations have different input lengths") n = min(ia.remaining(), ib.remaining()) ca = ia.component() cb = ib.component() a_piece = ia.take(n) b_piece = ib.take(n) if isinstance(ca, int) and isinstance(cb, int): if ca >= 0 and cb >= 0: _append_component(ap, n) _append_component(bp, n) elif ca < 0 and cb >= 0: _append_component(ap, -n) elif ca >= 0 and cb < 0: _append_component(bp, -n) else: # Both delete the same source characters. pass else: raise TypeError("invalid OT component pair") return ap, bp def append_operation(text: str, inserted: str) -> Operation: n = utf16_len(text) return [inserted] if n == 0 else [n, inserted] def insert_operation(text: str, pos: int, inserted: str) -> Operation: if not 0 <= pos <= len(text): raise ValueError("insert position outside document") pos_u = utf16_len(text[:pos]) tail_u = utf16_len(text) - pos_u op: Operation = [] if pos_u: op.append(pos_u) op.append(inserted) if tail_u: op.append(tail_u) return op def replace_operation(text: str, start: int, end: int, replacement: str) -> Operation: if not 0 <= start <= end <= len(text): raise ValueError("replace range outside document") start_u = utf16_len(text[:start]) end_u = utf16_len(text[:end]) tail_u = utf16_len(text) - end_u op: Operation = [] if start_u: op.append(start_u) if end_u - start_u: op.append(-(end_u - start_u)) if replacement: op.append(replacement) if tail_u: op.append(tail_u) return op @dataclass class PendingOperation: base_revision: int operation: Operation selection: dict[str, Any] @dataclass class HedgeDocDocument: text: str = "" revision: int = 0 selection: Optional[dict[str, Any]] = None clients: list[Any] = field(default_factory=list) remote_selections: dict[str, Optional[dict[str, Any]]] = field(default_factory=dict) last_operation_id: Optional[str] = None last_operation_client: Optional[str] = None class RevisionMismatch(RuntimeError): pass class HedgeDocClient: def __init__( self, url: str, note_id: str, cookie: Optional[str] = None, *, verbose: bool = True, on_remote_operation: Optional[Callable[[HedgeDocDocument], None]] = None, on_remote_operation_detail: Optional[Callable[[HedgeDocDocument, Operation], None]] = None, on_ack: Optional[Callable[[int], None]] = None, on_connection_state_changed: Optional[Callable[[bool], None]] = None, ): self.url = url.rstrip("/") self.note_id = note_id self.cookie = cookie self.verbose = verbose self.on_remote_operation = on_remote_operation self.on_remote_operation_detail = on_remote_operation_detail self.on_ack = on_ack # Called with True on connect, False on disconnect -- the ONLY thing # send_operation()/_emit_pending() do differently when offline is # nothing: they still optimistically update local state and queue # the operation (that's why local editing keeps working while # offline), then _emit_pending()'s sio.emit() raises BadNamespaceError # since python-socketio refuses to emit on a disconnected client -- # and nothing here resends a queued operation on reconnect. This # hook exists so a caller (Agent) can at least make that visible # instead of it being silent until someone notices data never # arrived on the server. self.on_connection_state_changed = on_connection_state_changed self.sio = socketio.Client(logger=False, engineio_logger=False) self.document = HedgeDocDocument() self._ready = threading.Event() self._lock = threading.RLock() self._connect_error: Optional[BaseException] = None self._pending: list[PendingOperation] = [] self._seen_operation_ids: set[str] = set() self.sio.on("doc", self._on_doc) self.sio.on("operation", self._on_operation) self.sio.on("ack", self._on_ack) self.sio.on("selection", self._on_selection) self.sio.on("cursor focus", self._on_cursor_focus) self.sio.on("cursor activity", self._on_cursor_activity) self.sio.on("cursor blur", self._on_cursor_blur) self.sio.on("*", self._on_any_event) self.sio.on("connect", self._on_connect) self.sio.on("disconnect", self._on_disconnect) self.sio.on("connect_error", self._on_connect_error) @property def pending_count(self) -> int: with self._lock: return len(self._pending) def _snapshot(self) -> HedgeDocDocument: return HedgeDocDocument( text=self.document.text, revision=self.document.revision, selection=self.document.selection, clients=list(self.document.clients), remote_selections=dict(self.document.remote_selections), last_operation_id=self.document.last_operation_id, last_operation_client=self.document.last_operation_client, ) def _on_connect(self): if self.verbose: logger.info("Socket.IO connected.") if self.on_connection_state_changed: self.on_connection_state_changed(True) def _on_disconnect(self): if self.verbose: logger.info("Socket.IO disconnected.") if self.on_connection_state_changed: self.on_connection_state_changed(False) def _on_connect_error(self, data): self._connect_error = RuntimeError(f"connect_error: {data!r}") self._ready.set() if self.verbose: logger.error("Socket.IO connect error: %r", data) def _on_doc(self, *args): if not args: return payload = args[0] if isinstance(payload, dict): text = payload.get("str", payload.get("text", "")) revision = payload.get("revision", 0) clients = payload.get("clients", []) else: text = payload revision = args[1] if len(args) > 1 else 0 clients = args[2] if len(args) > 2 else [] if not isinstance(text, str): raise TypeError(f"doc text must be str, got {type(text).__name__}") revision = int(revision) with self._lock: # HedgeDoc may emit another ``doc`` snapshot while a local # operation is already optimistic/pending. That snapshot can be # the pre-operation document at the same revision. Replacing our # optimistic text here would move the editor backwards and make a # perfectly valid EOF byte position look outside the document. # The operation/ack stream is authoritative once local edits are # pending, so keep the optimistic state until those operations have # been acknowledged. if self._pending: if self.verbose: logger.info( "Ignoring doc snapshot while local operations are pending: " "snapshot_revision=%d local_revision=%d pending=%d", revision, self.document.revision, len(self._pending), ) return if revision < self.document.revision: if self.verbose: logger.info( "Ignoring stale doc snapshot: revision=%d local_revision=%d", revision, self.document.revision, ) return self.document.text = text self.document.revision = revision self.document.clients = clients if isinstance(clients, list) else [] self.document.remote_selections.clear() self.document.last_operation_id = None self.document.last_operation_client = None if self.verbose: logger.info("Document loaded. revision=%d length=%d", revision, len(text)) self._ready.set() def _on_ack(self, *args): if not args: logger.error("Malformed ack event: no arguments") return revision = args[0] if isinstance(revision, (list, tuple)) and len(revision) == 1: revision = revision[0] try: revision = int(revision) except (TypeError, ValueError): logger.error("Invalid ack revision: %r", revision) return send_next: Optional[PendingOperation] = None with self._lock: if not self._pending: if revision > self.document.revision: self.document.revision = revision callback_revision = self.document.revision else: pending = self._pending[0] expected = pending.base_revision + 1 if revision != expected: # ACKs identify the server revision of that local op. It # can arrive after peer broadcasts, so never roll the # visible revision backwards. if revision > self.document.revision or revision < pending.base_revision: logger.error("Unexpected ACK revision: got %s, expected %s", revision, expected) return self._pending.pop(0) self.document.revision = max(self.document.revision, revision) self.document.selection = pending.selection callback_revision = self.document.revision if self._pending: next_op = self._pending[0] next_op.base_revision = self.document.revision send_next = next_op if self.verbose: logger.info( "ACK received. server revision=%s; local revision=%s; pending=%s", revision, callback_revision, self.pending_count ) if send_next is not None: self._emit_pending(send_next) if self.on_ack: self.on_ack(callback_revision) def _fetch_current_document(self) -> Optional[str]: """Fetch the server's current markdown when OT state is inconsistent.""" url = f"{self.url}/{quote(self.note_id, safe='')}/download" req = Request(url, headers={"Accept": "text/markdown"}) if self.cookie: req.add_header("Cookie", self.cookie) try: with urlopen(req, timeout=10) as response: data = response.read() return data.decode("utf-8") except Exception as exc: logger.error("Could not resync document from %s: %s", url, exc) return None def _resync_after_operation_mismatch( self, old_text: str, new_revision: int, client_id: str, operation_id: Optional[str], ) -> Optional[Operation]: """Recover when an incoming OT op does not match our local text. This is deliberately only used with no optimistic local operations. In that state the server operation is the next authoritative state, so fetching the current note and replacing our local snapshot is safer than guessing how to transform a malformed/divergent operation. """ if self._pending: logger.error( "Cannot resync safely while %d local operation(s) are pending.", len(self._pending), ) return None # This is a genuine last resort (apply_operation already raised), but # it has the same DB-lag exposure as the removed large_delete # shortcut above -- /download can still be stale here. A short # delay past HedgeDoc's 1s dirty-flush interval trades latency (on # an already-rare error path) for a much better chance of reading # post-operation content instead of pre-operation content. import time time.sleep(1.2) server_text = self._fetch_current_document() if server_text is None: return None replacement: Operation if old_text: replacement = [0, -utf16_len(old_text), server_text] else: replacement = [server_text] self.document.text = server_text self.document.revision = new_revision self.document.last_operation_id = operation_id self.document.last_operation_client = client_id if operation_id is not None: self._seen_operation_ids.add(operation_id) snapshot = self._snapshot() logger.warning( "Resynced document after OT mismatch: revision=%s old_length=%d new_length=%d", new_revision, len(old_text), len(server_text), ) if self.on_remote_operation: self.on_remote_operation(snapshot) if self.on_remote_operation_detail: self.on_remote_operation_detail(snapshot, replacement) return replacement def _on_operation(self, *args): if len(args) < 5: logger.error("Malformed operation event: %r", args) return client_id, new_revision, operation, selection, operation_id = args[:5] if not isinstance(client_id, str): logger.error("Invalid operation client_id: %r", client_id) return try: new_revision = int(new_revision) operation = normalize_operation(operation) except (TypeError, ValueError) as exc: logger.error("Invalid operation event: %s", exc) return if operation_id is not None and not isinstance(operation_id, str): operation_id = str(operation_id) with self._lock: if operation_id is not None and operation_id in self._seen_operation_ids: return local_revision = self.document.revision if new_revision != local_revision + 1: logger.error( "Revision mismatch: incoming NEW revision %s != local revision + 1 (%s)", new_revision, local_revision + 1, ) logger.error("Resync/get_operations is required.") return # NOTE: a "large delete -> fetch authoritative markdown via HTTP # download" shortcut used to live here. Removed: HedgeDoc's # /download route reads note.content from the DB, which is only # flushed from the live realtime document on a 1-second dirty # timer (lib/realtime.js: setInterval(..., 1000) + isDirty # check). Fetching immediately after receiving this exact # operation races that timer and can return content from BEFORE # this operation was applied -- e.g. an AI integration's # placeholder text ("Thinking...") instead of its real answer, # applied as if it were authoritative and never corrected. There # was never a real need for this shortcut: apply_operation and # transform_operations don't care about operation size. # Transform the peer operation through every optimistic local # operation. Each local op is also transformed against the # remaining peer op, preserving the visible local edits. remote = list(operation) for pending in self._pending: local_prime, remote_prime = transform_operations(pending.operation, remote) pending.operation = local_prime remote = remote_prime old_text = self.document.text snapshot_already_delivered = False try: self.document.text = apply_operation(old_text, remote) except (TypeError, ValueError) as exc: logger.error("Could not apply transformed remote operation: %s", exc) logger.error("Original operation: %r", operation) logger.error("Transformed operation: %r", remote) # Large server-side replacements (for example an AI agent # rewriting an Agent block) can expose a pre-existing local # document-length divergence. When no local edit is pending, # recover from HedgeDoc's authoritative markdown instead of # dropping the operation and leaving JOE stale. resynced = self._resync_after_operation_mismatch( old_text, new_revision, client_id, operation_id ) if resynced is None: return remote = resynced snapshot = self._snapshot() snapshot_already_delivered = True else: self.document.revision = new_revision self.document.last_operation_id = operation_id self.document.last_operation_client = client_id if operation_id is not None: self._seen_operation_ids.add(operation_id) snapshot = self._snapshot() self.document.remote_selections[client_id] = ( selection if isinstance(selection, dict) else None ) snapshot = self._snapshot() if self.verbose: logger.info( "Remote operation applied+transformed: client=%s revision=%s -> %s id=%r op=%r pending=%s", client_id, local_revision, new_revision, operation_id, operation, self.pending_count ) if not snapshot_already_delivered: if self.on_remote_operation: self.on_remote_operation(snapshot) if self.on_remote_operation_detail: self.on_remote_operation_detail(snapshot, remote) def _on_selection(self, *args): if len(args) >= 2 and isinstance(args[0], str): with self._lock: self.document.remote_selections[args[0]] = ( args[1] if isinstance(args[1], dict) else None ) if self.verbose: logger.info("Event 'selection': %r", args) def _on_cursor_focus(self, *args): if self.verbose: logger.info("Event 'cursor focus': %r", args) def _on_cursor_activity(self, *args): if self.verbose: logger.info("Event 'cursor activity': %r", args) def _on_cursor_blur(self, *args): if self.verbose: logger.info("Event 'cursor blur': %r", args) def _on_any_event(self, event, *args): known = {"doc", "operation", "ack", "selection", "cursor focus", "cursor activity", "cursor blur"} if self.verbose and event not in known: logger.info("Event %r: %r", event, args) def connect(self, headers: Optional[dict[str, str]] = None): from urllib.parse import urlencode connect_url = f"{self.url}/?{urlencode({'noteId': self.note_id})}" merged_headers = dict(headers or {}) if self.cookie: merged_headers["Cookie"] = self.cookie self.sio.connect( connect_url, socketio_path="socket.io", headers=merged_headers or None, transports=["websocket", "polling"], wait_timeout=10, ) def wait_ready(self, timeout: float = 10.0) -> HedgeDocDocument: if not self._ready.wait(timeout): raise TimeoutError("Timed out waiting for HedgeDoc doc event.") if self._connect_error: raise self._connect_error with self._lock: return self._snapshot() def _emit_pending(self, pending: PendingOperation): self.sio.emit("operation", (pending.base_revision, pending.operation, pending.selection)) if self.verbose: logger.info("Sent operation at base revision=%s: %r", pending.base_revision, pending.operation) def send_operation(self, operation: Operation, selection: Optional[dict[str, Any]] = None): selection = selection or {"ranges": []} with self._lock: base_revision = self.document.revision if not self._pending else self._pending[-1].base_revision # Validate against the currently visible document before changing it. new_text = apply_operation(self.document.text, operation) pending = PendingOperation(base_revision, list(operation), selection) was_empty = not self._pending self._pending.append(pending) self.document.text = new_text self.document.selection = selection if was_empty: self._emit_pending(pending) elif self.verbose: logger.info("Buffered local operation; pending=%s", self.pending_count) def append(self, inserted: str, selection: Optional[dict[str, Any]] = None): with self._lock: operation = append_operation(self.document.text, inserted) new_length = utf16_len(self.document.text) + utf16_len(inserted) if selection is None: selection = {"ranges": [{"anchor": new_length, "head": new_length}]} self.send_operation(operation, selection) def insert(self, pos: int, inserted: str, selection: Optional[dict[str, Any]] = None): with self._lock: operation = insert_operation(self.document.text, pos, inserted) new_pos = utf16_len(self.document.text[:pos]) + utf16_len(inserted) if selection is None: selection = {"ranges": [{"anchor": new_pos, "head": new_pos}]} self.send_operation(operation, selection) def replace(self, start: int, end: int, replacement: str, selection: Optional[dict[str, Any]] = None): with self._lock: operation = replace_operation(self.document.text, start, end, replacement) new_pos = utf16_len(self.document.text[:start]) + utf16_len(replacement) if selection is None: selection = {"ranges": [{"anchor": new_pos, "head": new_pos}]} self.send_operation(operation, selection) def close(self): if self.sio.connected: self.sio.disconnect()