Skip to content

terminal: independent sessions, pointer UX and honest lifecycle (stage 4) - #167

Merged
ccclosed merged 12 commits into
devfrom
feat/term-ux-lifecycle
Nov 22, 2026
Merged

ccclosed merged 12 commits into
devfrom
feat/term-ux-lifecycle

Conversation

@ccclosed

Copy link
Copy Markdown
Owner

Что это

Stage 4 терминального окна: окно перестаёт быть «зеркалом одного shell» и
становится настоящим терминалом с изоляцией и жизненным циклом. Базируется на
dev + merge #147 (#147 пока OPEN — при его слиянии диф станет чистым).

Kernel

  • MAX_SESSIONS 2 → 4: слоты 1..3 — свои offscreen-поверхность, кольцо ввода,
    указатель и cwd. /dev/vtfb{N}/vtinput{N}/vtmouse{N} на слот; слот
    эксклюзивен для окна (EBUSY), счётчик открытых fd на слот (закрытие второго
    окна не гасит первое), повторный open того же клиента — не занятость.
    Задача сессии находит слот по pid-владельцу (два спавна подряд не перепутают
    сессии).
  • /dev/vtmouse{N} — 16-байтные записи x/y/кнопки/колесо; ps2_mouse::poll()
    маршрутизируется по задаче. Отсюда колесо (scrollback), выделение протяжкой и
    копирование/вставка (Ctrl+Y/Ctrl+V) работают в окне через существующие
    shell/selection.rs/clipboard, без правок их логики.
  • Фокус клавиатуры: ioctl(/dev/vtinput{N}, VTINPUT_SET_FOCUS); пока фокус у
    окна, deliver_physical не дублирует физические клавиши в boot-кольцо (иначе
    каждая буква терминала печаталась бы и в boot-shell). Фокус сбрасывается при
    выходе сессии.
  • errno::EBUSY (16); lseek/ftruncate/stat/ioctl — по номеру сессии.

Клиент pagh-terminal

  • Авто-подключение к свободному слоту (EBUSY → следующий), --vt-fb/--vt-input/ --vt-mouse; без указателя окно работает (честная строка в лог).
  • MouseForwarder: PDP/1 Motion/Button/Axis → записи /dev/vtmouse{N};
    координаты окна → пиксели поверхности через тот же fit_placement; маска
    кнопок и знак колеса переводятся в соглашение ядра.
  • exit → ENODEV: окно показывает «сессия завершена»; Enter поднимает новую
    сессию в том же окне, Esc закрывает. Старые fd закрываются до open.
  • Фокус из Focus/configure → ioctl(0x4710).

Честные ограничения

  • Нет PTY/termios/TIOCGWINSZ; одна foreground-группа на ядро (per-window job
    control — нет).
  • drivers::vt не реализует alternate screen (\e[?1049h) и application
    cursor keys: полноэкранные редакторы kernel-shell (nano, paint) рисуют
    сами, ncurses через lxrun остаётся построчным.
  • Буфер обмена — сессионный (мышь + Ctrl+Y/Ctrl+V), системного нет.
  • Ввод окна требует отсутствия foreground-совместимого процесса (документировано).

Проверки

  • Гейты 6/6 (fmt, debug, release, host, safety, agents-md).
  • Host: 860 свойств (P68 — ABI указателя).
  • pagh-terminal: 179 host-тестов (включая pointer ABI/координаты/фокус-хелперы).
  • In-QEMU selftest: указатель на слот + второе окно/EBUSY/изоляция.
  • Live-QEMU tools/e2e.py termux: история, редактирование (Home/End/backspace →
    имя+содержимое файла), scrollback, выделение+Ctrl+Y, nano, exit→Enter,
    20 закрытий/переоткрытий, два окна; serial без утечек ввода и без #PF.
    Evidence: /home/oleg/.cache/pagh-agent-notes/qterm4-live/.

НЕ мержить — lead review.

ccclosed pushed a commit that referenced this pull request Nov 21, 2026
Lead decision: the client keeps a single restart path, the one #167 extends. The
parallel `awaiting_respawn`/`notice_pending` flags are gone; ENODEV now goes
through `wait_for_restart` with #167's name, signature, notice text and key
semantics: Enter/Space restarts the session in this window, Esc (or a server
close) closes it. `draw_notice_frame` is the same helper #167 uses to put the
notice on screen, so merging the branches does not change behaviour.

`respawn_kernel_session` stays as the #147-specific mechanics behind that door:
close both old devices, then reopen input and surface, so the kernel's
open-counter cannot drop to zero between the two opens (that is what made the
first restart attempt answer ENODEV). The log line the live acceptance greps
("kernel session restarted in the same window (generation N)") is unchanged.

174 host tests green; docs describe Enter/Space vs Esc.
@ccclosed
ccclosed force-pushed the feat/term-ux-lifecycle branch from ed79a62 to df42fdc Compare November 22, 2026 07:30
…keyboard focus

The terminal window was only a viewer of one shared shell session: a second
window reused slot 1 (same pixels, same input, same cwd), the pointer was the
boot PS/2 state (so wheel/selection inside a window did nothing or acted on the
boot console), and every physical scancode was also pushed into the boot shell
because only `/dev/vtinput` (the VT mirror) had a dedup latch. Stage 4 makes the
window a real terminal and keeps input honest:

* `MAX_SESSIONS` 2 -> 4: slots 1..3 have their own offscreen surface, key ring,
  pointer state and `cwd`; `/dev/vtfb{N}`/`vtinput{N}`/`vtmouse{N}` are created
  per slot. A slot is exclusive to one client (`EBUSY` for another window) and
  the open counter is per slot, so closing window B no longer reaps window A.
  Repeated opens from the same client are not "busy" (one window opens three
  devices). The session task finds its slot by owner pid instead of a shared
  pending slot, which two back-to-back spawns could overwrite.
* `/dev/vtmouse{N}` (16-byte LE records: x, y, buttons, wheel) plus
  `vt_mouse::write_session`; `ps2_mouse::poll()` now routes by task, so shell,
  `nano` and `paint` read the window's pointer without any change of their own.
  That is what makes wheel scrollback, drag selection and copy/paste (Ctrl+Y /
  Ctrl+V) work in the window: those live in `shell/selection.rs` and only ever
  needed the session's pointer.
* Keyboard focus: `ioctl(/dev/vtinput{N}, VTINPUT_SET_FOCUS)` tells the kernel a
  window owns the keyboard. While it does, `deliver_physical` does not push the
  key into the boot shell's ring — the client already forwards it through
  `vtinput{N}`, and without this every character typed in a terminal also typed
  into the boot prompt. Focus is cleared on session exit, so a dead client can
  never swallow the boot keyboard.
* `errno::EBUSY` (16) for the exclusive-slot refusal; `lseek`/`ftruncate`/stat
  and ioctl dispatch now key off the session number instead of "is vtfb1".

Tests: in-QEMU `terminal-session::pointer input is isolated per slot` (partial
writes assemble, boot pointer untouched, reset forgets), and `second window is
its own session; busy slots are EBUSY` (isolation of input/cwd, EBUSY for a
foreign client, both tasks reaped on the last close); host property P68 for the
pointer ABI (round trip, button mask, clamp, stream split across write(2)).
…r exit

The window hardcoded `/dev/vtfb1`/`/dev/vtinput1`: a second terminal reused the
same shell (two windows = one session), wheel and selection did nothing (they
were ignored as "kernel's business" without a channel to the kernel), and `exit`
in the session closed the window, so the only reconnect was relaunching the app
from the desktop.

* Session auto-attach: with no explicit `--vt-fb`, the client tries slots
  1..8 and takes the first that opens; `EBUSY` means the slot is another window,
  `ENOENT` ends the scan. Input/pointer paths follow the slot
  (`/dev/vtinput{N}`, `/dev/vtmouse{N}`). Kernel without the pointer device still
  gets a working window (keyboard works; the missing pointer's consequence is
  logged, not faked).
* Pointer: `MouseForwarder` maps PDP/1 `Motion`/`Button`/`Axis` to 16-byte
  `/dev/vtmouse{N}` records. Coordinates are converted from window pixels back
  to *surface* pixels with the same `fit_placement` used for the blit (letterbox
  points clamp to the edge), the PDP button mask is translated to the kernel's
  bit order, and the wheel sign is inverted once (PDP/REL_WHEEL +1 = away from
  the user, PS/2 IntelliMouse -1, which the kernel shell expects).
* Lifecycle: `ENODEV` is no longer fatal. The window shows "the shell session has
  ended / Press Enter to start a new session, Esc to close", and Enter reopens
  the device set in place (old fds closed first), invalidates the frame and
  resumes. A replacement that cannot be opened says why and closes on Esc.
* Focus: `Focus`/`configure` flags are reported to the kernel with
  `ioctl(0x4710)` on the input fd, so a focused window stops the duplication of
  physical keys into the boot shell. `ENOTTY` (older kernel) is logged once and
  does not break input.

Tests: `tests/kernel_session.rs` grows the pointer ABI (16-byte record layout,
button mapping, wheel sign, window->surface inverse, `MouseForwarder` output and
failed sink) and `--help` coverage; 179 crate tests pass. `TERMINAL.md`/README
describe the new devices, focus and restart; docs are committed separately.
…docs

Adds a live acceptance mode that drives the REAL compositor and REAL
pagh-terminal over QEMU PS/2 input and verifies the result from marker files
written to the ext2 data disk (not from "the screenshot looked right"):

* history: a command is recalled with Up and runs again (/mnt/q1);
* editing: Home + Right×5 + insert + End + Backspace produce a file whose NAME
  and content only exist if the caret really moved (/mnt/q2Z = "CDAB");
* scrollback: a screenful of `help`, wheel up and back (screenshot pair);
* selection + Ctrl+Y paste: an appending command is run, its line is dragged
  over with the pointer, pasted and executed (/mnt/q4 has two lines);
* nano (alternate screen) with cursor keys, Esc back, then a shell command;
* exit -> ENODEV notice -> Enter restarts in the same window (/mnt/q7);
* 20 close(X)/reopen(Ctrl+Alt+T) cycles, each proving a live session by
  running a command that appends to /mnt/r (20 lines expected);
* two windows typed into separately (/mnt/q9one, /mnt/q9two) with the client
  log showing slots 1 and 2, and the serial log asserted free of the typed
  text (boot-VT isolation) and of #PF/panic lines.

Pointer aiming is calibrated from two framebuffer dumps (relative PS/2 only),
so clicks on the title-bar close button and drags are aimed, not guessed.
`docs/terminal-session.md` documents the new ABI (`vtmouse`, focus ioctl),
multi-slot lifecycle and the honest boundaries (no alternate screen in
vt.rs, session-scoped clipboard, single tty foreground group).
The compositor only sends `Focus` when focus *changes*. After `exit` + Enter the
window stays focused from the compositor's point of view, so the restarted
session never got `VTINPUT_SET_FOCUS` and physical keys were (again) duplicated
into the boot shell. Track the last known focus and re-apply it to the new
`/dev/vtinput{N}` fd after reopening.

e2e: termux parser needs --serial-start-timeout (the shared disk-preparation
helper reads it; the mode crashed before its first boot without the flag).
…e proof

Three findings from the live run (tools/e2e.py termux), each a real defect:

* Wheel sign: `Axis.vertical` is already the kernel's own `REL_WHEEL` value
  (the compositor forwards the evdev stream), so inverting it made wheel-up
  scroll towards newer text. Forward it unchanged; docs and tests follow.
* Window id: kernel-session mode used the fixed id 101. If a window from the
  previous client still existed (the common case when relaunching a terminal),
  `create` was rejected as duplicate and the second attempt died. Derive the id
  from the pid (unique among live processes); `--window-id` still overrides it
  for tests. New fake-compositor test asserts kernel mode does not use 101.
* Live proof needed a channel the shell actually has: it has no `>` redirection
  (it echoes `>` and the path), so the acceptance's marker files never existed.
  `tools/termux_marker.c` is a freestanding raw-syscall program that appends its
  arguments to a file; commands are `lxrun /mnt/marker /mnt/q2 CDAB`.

The e2e mode now builds/injects the marker, uses closed-loop pointer aiming for
the 22x22 close button (open-loop tracking drifted ~85 px and the X was missed),
checks the wheel by pixel diff, and requires 20 server Close events in the
client log.
…llback

Live measurement corrected two assumptions:

* Wheel sign: with `Axis.vertical` forwarded unchanged, wheel-up produced no
  frame change while wheel-down scrolled (up=49, down=2656 changed samples).
  The client must invert once: the compositor carries QEMU/REL_WHEEL's sign
  (`wheel-up` → negative), while kernel-shell's `ps2_mouse` uses the
  IntelliMouse convention and computes `lines = -delta`. Docs/tests follow.

* Pointer aim: open-loop relative tracking drifts ~85 px over a few moves
  (random PS/2 packet loss under TCG, not a fixed scale — compensating for the
  measured ratio made it worse). Aiming now homes into the (0,0) clamp, probes
  +40 px, locates the sprite in two framebuffer dumps and steps back before
  clicking (the probe itself moved the pointer 40 px off target, which made
  every "close" click hit the neighbouring title-bar button).

The scrollback check now also uses PageUp/PageDown as an independent path and
waits for a stable frame instead of a fixed delay (a wheel sent mid-`help` is
absorbed by the shell's prompt-boundary reset).
…inates

* `--reuse-desktop-disk` kept q1/q2/q4/q6/q7/term.log from the previous run;
  append-count checks then passed or failed for the wrong reason. Remove the
  data files (not the marker binary) before boot.
* Compositor input coordinates are content-relative (0..900, 0..600), not
  screen-absolute. The selection drag used the screen row (y=120, surface row 7)
  and started at x=98, skipping the command's first characters; use the
  letterbox offset (y≈25) and start at x=2. This is why Ctrl+Y re-ran only a
  fragment (or nothing) although the selection machinery itself worked.
* Skip the slot-2 log check in QUICK mode (no second window is opened there).
@ccclosed
ccclosed force-pushed the feat/term-ux-lifecycle branch from df42fdc to 746efa3 Compare November 22, 2026 07:43
… tty

Conflicts (8 files) and their resolution:

* `src/drivers/session.rs` — `exit()` keeps our per-slot `OPEN_FDS`/`OPEN_CLIENT`
  reset AND #172's `jobs::clear_session` + `tty::reset_session`; added
  `open_client(session)` for the focus-aware keyboard latch.
* `src/drivers/vtinput.rs` — `write_session` takes #172's PTY path
  (`fg_pid(session)` + `deliver_to_job`: raw→stdin queue, cooked→ISIG +
  session scancode ring). The window keeps #172's physical-keyboard latch, but
  it is now **focus-aware**: `VTINPUT_SET_FOCUS(true)` re-claims it for the
  slot's client and `false` releases it, so clicking the desktop returns the
  keyboard to the boot shell instead of waiting for the window to close.
  `deliver_physical` still suppresses the boot ring while any focused session
  is live.
* `src/arch/x86_64/linux/io_sys.rs` — one dispatch for any `vtinput{N}`:
  our `VTINPUT_SET_FOCUS` first, otherwise #172's per-session
  `tty_ioctl(session, …)` (winsize/SIGWINCH, TIOCGPGRP/SPGRP). vtfb dispatch
  stays session-indexed (slots 1..3), console/stdin use #172's tty_ioctl with
  the task's session.
* `src/drivers/README.md` — our vtinput/vtmouse/session rows, with the latch
  described as focus-aware and #172's PTY/pass-through facts.
* `rust-apps/pagh-terminal/src/bin/pagh-terminal.rs` — our slot scan/EBUSY,
  `--vt-mouse`, `MouseForwarder`, pid-derived window id and focus ioctl kept;
  #172's `forward_winsize` (`TIOCSWINSZ` on the key sink, re-sent after
  respawn) merged into the same loop. A stray `KeyForwarder::new(key_sink)`
  from the merged side removed (devices already carry the forwarder), and
  winsize forwarding goes through `keys.sink()`, not the mouse option.
* `src/kernelsession.rs` — our `MouseForwarder` + #172's `file()`; duplicate
  `file()` impl removed (kept #172's, which returns `Option<&File>` for the
  close/respawn window).
* `src/tests/kernel_session.rs` — our pointer/EBUSY/window-id tests and
  #172's `winsize_cells` test both kept.
* `TERMINAL.md`, `docs/terminal-session.md` — #172's §1.5 (per-session
  foreground group, TOSTOP off by default, TIOCGWINSZ/TIOCSWINSZ/SIGWINCH,
  per-session jobs) documented as working; our vtmouse/focus/multi-slot
  sections kept; the old "no job control / no winsize / TOSTOP mandatory"
  claims dropped as outdated. Remaining gaps: no /dev/pts, no real pixel
  resize, DEC/alternate screen, session-scoped clipboard, max 3 windows.

Not broken: job control keeps its per-session fg pgid/TOSTOP/SIGWINCH; the
only changed interaction is that the keyboard latch now follows compositor
focus, which is what makes Ctrl+C/Ctrl+Z in a window hit that window only
while still returning the keyboard to the boot shell after a desktop click.
@ccclosed
ccclosed merged commit f1453f5 into dev Nov 22, 2026
8 checks passed
@ccclosed
ccclosed deleted the feat/term-ux-lifecycle branch November 22, 2026 10:34
ccclosed added a commit that referenced this pull request Nov 22, 2026
…dow acceptance

Resolve the two conflicts by taking dev's versions of the tooling and
re-adding only what #171 still owns on top:

* tools/e2e.py — dev's file (termux stage-4 mode included) + the
  'termwindow' mode re-inserted on top of its helpers. _desktop_bins and
  _desktop_prepare_disk are reused; the latter gains the optional
  size_mb argument (64 MiB default keeps every existing mode unchanged),
  because ppkg install needs a 256 MiB volume.
* docs/terminal-session.md — dev's rewritten §6 kept; a short §7 documents
  the live acceptance and points at §6.10 (no alternate screen/DEC modes)
  instead of claiming ncurses interactivity.
* tools/README.md — dev's text kept, mode table lists termux and
  termwindow, the termwindow bullet matches what the mode now does
  (ncurses-base, -I, unverified ncurses interactivity).
* tools/qemu_shot.py — unchanged addition: dev does not have chord
  support, and the mode needs 'ctrl-s'/'ctrl-o' via HMP.

The Linux (ncurses) nano step is now recorded as info_check (unverified)
when the editor reaches read(2) but never accepts the chords: that is the
named §6.10 limitation of drivers::vt, not a stage-2 window-session claim.
ccclosed pushed a commit that referenced this pull request Nov 22, 2026
Sync with dev=f1453f55 (#167 multi-session terminal lifecycle on top of
#172 PTY job control): /dev/vtfbN, /dev/vtinputN and /dev/vtmouseN per
session instead of the single-session vtfb1/vtinput1 pair.

Conflicts:
- src/arch/x86_64/linux/io_sys.rs (4 stops): merged the dev per-session
  accessors with the USB hooks.
  * read: `/dev/uevent` record path stays before the dev
    `vtconsole || vtfb_session().is_some()` snapshot path.
  * close: dev `closing_session` (vtfb/vtinput/vtmouse) and USB
    `closing_uevent` both release their reader/session.
  * stat mode: dev session accessors plus `is_uevent()` stay S_IFCHR.
  * ioctl: fbdev -> vtconsole -> vtfb_session -> uevent -> vtinput_session
    (with the dev VTINPUT_SET_FOCUS/tty_ioctl split) -> Console/Stdin.
- src/vfs/mod.rs: dev terminal_devices loop (vtfb/vtinput/vtmouse per
  MAX_SESSIONS) is kept, and `/dev/block` + `/dev/uevent` are chained into
  the same DevDirectory children list.
- src/arch/x86_64/linux/errno.rs auto-merged with a duplicate `EBUSY=16`
  (USB needed it, #167 added its own); collapsed to one variant with both
  documented meanings.
- src/test.rs auto-merged; all three routines remain (console grid,
  linux-tty per-session, USB layout).

The dead `vtinput1_ioctl` wrapper superseded by the dev inline
session-aware branch is removed.

Post-merge evidence: gates 6/6 (host 903/0), QEMU usb-storage acceptance
46/46, release-kernel selftest 129 routines / 0 failed / 1 skipped
(NVMe absent), one flocked run.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant