#!/usr/bin/env python3 """The per-user daemon end to end (docs/next-daemon.md, phase 3), under a private HOME and runtime directory: - a terminal's session detached (the stub ends, exit 0) and attached again from another terminal, N times; - a session killed outright: its shells live on, held by the daemon, and another session adopts them as terminal panes; - nothing left behind: no session, shell, daemon or socket. python3 -B test/daemon.py [cycles] python3 -B test/daemon.py --gui [cycles] (a hidden window; needs a Wayland display, and a pardes beside it for the refusal) """ import fcntl import os import shutil import signal import struct import subprocess import sys import tempfile import termios import threading import time from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from ninep import Client # noqa: E402 def wait_for(what, check, timeout=10): deadline = time.monotonic() + timeout while True: got = check() if got: return got if time.monotonic() > deadline: raise TimeoutError(what) time.sleep(.01) class Term: """A terminal: a pty whose other end is read and kept, its frame requests answered (CSI 5 n), as a terminal emulator does.""" def __init__(self, rows=24, cols=80): self.master, self.slave = os.openpty() fcntl.ioctl(self.slave, termios.TIOCSWINSZ, struct.pack('HHHH', rows, cols, 0, 0)) self.out = bytearray() self.lock = threading.Lock() self.reader = threading.Thread(target=self.drain, daemon=True) self.reader.start() def drain(self): while True: try: got = os.read(self.master, 65536) except OSError: return if not got: return with self.lock: self.out += got if b'\x1b[5n' in got: try: os.write(self.master, b'\x1b[0n') except OSError: return def spawn(self, argv, env): slave = self.slave return subprocess.Popen(argv, env=env, stdin=slave, stdout=slave, stderr=slave, start_new_session=True, preexec_fn=lambda: fcntl.ioctl(0, termios.TIOCSCTTY, 0)) def text(self): with self.lock: return bytes(self.out) def close(self): os.close(self.slave) os.close(self.master) self.reader.join(timeout=2) def run(client, serial, line): """pty/run: a line in, `exit N` and its output out.""" fid = client.open(f'/pane/{serial}/pty/run', 2) try: client.rpc(118, struct.pack('