From 7679f6a3eff84b09865f809a80227522842843dd Mon Sep 17 00:00:00 2001 From: pagh-agent Date: Thu, 19 Nov 2026 13:12:15 +0300 Subject: [PATCH 01/12] terminal: attach the window to the kernel shell session by default MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The windowed terminal spawned a private userspace shell over two pipes (`--shell-child`), so the window could only ever offer help/ls/cd/pwd/echo/cat/ uname/clear/exit. Everything the user actually wants — df/ps/ppkg/lxrun/id/ groups/su/login/disk/nano, history, line editing, scrollback — lives in the kernel shell, and a pixel copy of a kernel session can be rendered without rewriting that shell or inventing a PTY. `--socket PATH` without `--vt`/`--mirror-vt`/`--demo-shell`/`--pipe-shell` now opens /dev/vtfb1 (ioctl 0x4700 -> {width,height,stride,bpp=32,generation}, mmap PROT_READ/MAP_SHARED of stride*height) and /dev/vtinput1. Each iteration polls the generation header; only when it grows does the client blit the whole frame into the window canvas and forward damage over PDP/1 (ShmSurface when the compositor offers it). Keys go through keys::encode_key and are written to /dev/vtinput1 verbatim; the client renders and forwards input, it never fakes a command. `exit` in the session makes the device return ENODEV: the window shows "the shell session has ended / relaunch to reconnect", holds it briefly and closes. Reconnect is a relaunch by choice: the kernel spawns a session on the first open, and an in-window reconnect prompt would need a keyboard UI the pixel mirror does not have. Blit policy (documented in fit_placement): window >= surface -> exact 1:1, centred, no resampling; window smaller -> aspect-preserving nearest-neighbour downscale, centred, letterboxed with the theme background. Never cropped (losing part of a session's output is worse than losing a pixel row) and never upscaled (blurred magnification is worse than a crisp centred frame). Failure behaviour is explicit, never a silent demo: * devices missing (ENOENT, kernel without the surface) -> honest stderr line and the previous pipe shell session as the fallback; * devices present but ioctl/mmap/read/write failing -> honest message in the window, exit code 2, no fallback; * mmap unavailable -> documented read() snapshot fallback (header + pixels). All device I/O hides behind `kernelsession::{FrameSource, InputSink}` because the library crate forbids unsafe; only the thin ioctl/mmap glue lives in the binary (src/bin/pagh-terminal/devfs.rs). That is what makes this testable: host CI has no /dev/vtfb1. `tests/kernel_session.rs` drives generation, blit (1:1/downscale/letterbox), frame-1-only redraws, invalidate-for-full-repaint, short frames, ENODEV/IO errors, key encoding, FileInput, read() fallback on a real file, the notice renderer, --help, the missing-device fallback and the honest error for a broken surface. Existing demo/pipe paths are unchanged but now explicit (`--demo-shell`, `--pipe-shell`); the three e2e tests that drive them pass the flag instead of relying on the old default. Kernel side is not touched: this is the client half of a contract implemented in parallel; live integration is still pending, so nothing here claims QEMU verification. --- .../pagh-terminal/src/bin/pagh-terminal.rs | 523 +++++++++++- .../src/bin/pagh-terminal/devfs.rs | 174 ++++ rust-apps/pagh-terminal/src/kernelsession.rs | 778 ++++++++++++++++++ rust-apps/pagh-terminal/src/lib.rs | 6 +- rust-apps/pagh-terminal/src/render.rs | 24 + rust-apps/pagh-terminal/tests/headless_cli.rs | 2 +- .../pagh-terminal/tests/kernel_session.rs | 583 +++++++++++++ rust-apps/pagh-terminal/tests/pdp_e2e.rs | 9 +- rust-apps/pagh-terminal/tests/shm_e2e.rs | 3 + 9 files changed, 2079 insertions(+), 23 deletions(-) create mode 100644 rust-apps/pagh-terminal/src/bin/pagh-terminal/devfs.rs create mode 100644 rust-apps/pagh-terminal/src/kernelsession.rs create mode 100644 rust-apps/pagh-terminal/tests/kernel_session.rs diff --git a/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs b/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs index d1dd7a50..be0665f2 100644 --- a/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs +++ b/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs @@ -2,19 +2,38 @@ //! //! Modes: //! +//! * `--socket PATH` (default windowed mode): attach to the **kernel shell +//! session** — blit `/dev/vtfb1` pixels into the window and forward keys to +//! `/dev/vtinput1`. The kernel owns the shell: commands, echo, line editing +//! and scrollback are its, the client only renders and forwards input. //! * `--headless` (default without a socket): parse a script or built-in demo, //! print the text and/or write a PNG. -//! * `--socket PATH`: connect to the desktop compositor, create a window, -//! upload frames and process input events. -//! * `--vt PATH`: read snapshots from the proposed kernel VT console shared -//! surface and send input to `/dev/vtinput` (ABI v1, see TERMINAL.md). +//! * `--vt PATH`: read snapshots from the kernel VT console shared text surface +//! and send input to `/dev/vtinput` (ABI v1, see TERMINAL.md). With +//! `--socket` this is the legacy window paths: `--mirror-vt` mirrors the boot +//! VT, otherwise the private userspace shell session starts. +//! * `--pipe-shell` / `--demo-shell`: explicit test/fallback window modes (the +//! private userspace shell over pipes, and the built-in demo shell). +//! +//! The mmap/ioctl glue for the kernel-session devices lives in the `devfs` +//! submodule: the library crate forbids `unsafe`, so every unsafe call sits here. + +// Explicit path: cargo auto-discovers every `*.rs` directly under `src/bin/` as +// a binary target, so the module lives in the `pagh-terminal/` subdirectory and +// is named here instead of being a second (empty) bin. +#[path = "pagh-terminal/devfs.rs"] +mod devfs; use std::path::PathBuf; use std::process::ExitCode; use std::time::{Duration, Instant}; -use pagh_terminal::client::{close_name, error_name, Event, SurfaceClient}; +use pagh_terminal::client::{close_name, error_name, Event, ShmFrame, SurfaceClient}; use pagh_terminal::demo::{self, DemoShell}; +use pagh_terminal::kernelsession::{ + is_missing_device, is_session_end, render_notice, Draw, FileInput, KernelFrame, KeyForwarder, + VtFbError, +}; use pagh_terminal::keys::{self, KeyModes}; use pagh_terminal::protocol::{buttons, InputEvent}; use pagh_terminal::render::{ @@ -28,12 +47,28 @@ use pagh_terminal::Terminal; const VERSION: &str = "0.1.0"; +/// Kernel shell-session pixel surface (mode default). +const KERNEL_FB: &str = "/dev/vtfb1"; +/// Kernel shell-session input device. +const KERNEL_INPUT: &str = "/dev/vtinput1"; +/// Boot VT text surface (legacy `--vt`/`--mirror-vt`). +const MIRROR_VT: &str = "/dev/vtconsole0"; +/// Boot VT input device (legacy mirror). +const MIRROR_INPUT: &str = "/dev/vtinput"; +/// Сколько держать в окне честное сообщение «сессия завершена/ошибка» перед +/// закрытием окна. +const NOTICE_HOLD: Duration = Duration::from_millis(1500); + #[derive(Debug)] struct Args { headless: bool, socket: Option, vt: Option, - vt_input: String, + /// Input device override; per-mode default (`/dev/vtinput` for the boot-VT + /// mirror, `/dev/vtinput1` for the kernel session) when absent. + vt_input: Option, + /// Pixel surface of the kernel shell session (default `/dev/vtfb1`). + vt_fb: String, size: (u32, u32), cols: Option, rows: Option, @@ -57,8 +92,13 @@ struct Args { /// `--shell-child` mode). Used to drive a real shell once one exists. shell_cmd: Option, /// Keep the old windowed behaviour: mirror the kernel boot VT instead of - /// starting a private shell session. + /// attaching to the kernel shell session. mirror_vt: bool, + /// Explicit window mode: the private userspace shell over two pipes + /// (fallback/test path of the kernel-session mode). + pipe_shell: bool, + /// Explicit window mode: the built-in demo shell (screenshots, `--feed`). + demo_shell: bool, help: bool, version: bool, } @@ -69,7 +109,8 @@ impl Default for Args { headless: false, socket: None, vt: None, - vt_input: "/dev/vtinput".to_string(), + vt_input: None, + vt_fb: KERNEL_FB.to_string(), size: (900, 600), cols: None, rows: None, @@ -93,12 +134,26 @@ impl Default for Args { shell_child: false, shell_cmd: None, mirror_vt: false, + pipe_shell: false, + demo_shell: false, help: false, version: false, } } } +impl Args { + /// Where the boot-VT mirror writes VT input bytes. + fn mirror_input(&self) -> &str { + self.vt_input.as_deref().unwrap_or(MIRROR_INPUT) + } + + /// Where the kernel-session mode writes VT input bytes. + fn kernel_input(&self) -> &str { + self.vt_input.as_deref().unwrap_or(KERNEL_INPUT) + } +} + fn main() -> ExitCode { match run() { Ok(()) => ExitCode::SUCCESS, @@ -133,9 +188,29 @@ fn run() -> Result<(), String> { if let Some(vt) = &args.vt { return run_vt(&args, vt); } - if let Some(socket) = &args.socket { + // `--mirror-vt` without an explicit `--vt` path means the boot VT console. + if args.mirror_vt { + return run_vt(&args, MIRROR_VT); + } + // Explicit non-default window modes (tests, screenshots, A/B comparison). + if args.demo_shell || args.feed.is_some() { + let socket = args + .socket + .as_deref() + .ok_or("--demo-shell/--feed require --socket")?; return run_client(&args, socket); } + if args.pipe_shell { + let socket = args + .socket + .as_deref() + .ok_or("--pipe-shell requires --socket")?; + return run_shell_session(&args, socket); + } + if let Some(socket) = &args.socket { + // Default windowed mode: attach to the kernel shell session. + return run_kernel_session(&args, socket); + } run_headless(&args) } @@ -565,10 +640,13 @@ fn run_vt(args: &Args, path: &str) -> Result<(), String> { let bytes = keys::encode_key(code, pressed, modifiers, &modes); if !bytes.is_empty() { if let Err(error) = - pagh_terminal::vtconsole::send_input(&args.vt_input, &bytes) + pagh_terminal::vtconsole::send_input(args.mirror_input(), &bytes) { if !input_error_reported { - eprintln!("pagh-terminal: cannot write {}: {error}", args.vt_input); + eprintln!( + "pagh-terminal: cannot write {}: {error}", + args.mirror_input() + ); input_error_reported = true; } } @@ -889,6 +967,383 @@ fn run_shell_session(args: &Args, socket: &str) -> Result<(), String> { } } +/// Оконный режим по умолчанию: сессия ядра (`/dev/vtfb1` + `/dev/vtinput1`). +/// +/// Ядро владеет shell'ем целиком — командами, эхом, редактированием строки, +/// history и scrollback'ом; клиент блитит пиксели его поверхности и передаёт +/// клавиатуру VT-байтами. Ни одна команда здесь не имитируется: если +/// устройство не отвечает, окно говорит об этом прямо. +/// +/// Поведение при отказе: +/// +/// * `/dev/vtfb1` (или `/dev/vtinput1`) отсутствует — старое ядро: честная +/// строка в stderr и откат на прежнюю pipe-сессию с userspace-shell'ом; +/// * устройство есть, но ioctl/mmap/read/write не работают — честное сообщение +/// **в окне** и выход с кодом 2, без отката в демо; +/// * `exit` в сессии (`ENODEV`): сообщение «сессия завершена», окно закрывается. +/// Реконнект — повторный запуск окна: первый `open` спавнит новую сессию. +fn run_kernel_session(args: &Args, socket: &str) -> Result<(), String> { + let fb_path = args.vt_fb.as_str(); + let input_path = args.kernel_input(); + + let source = match devfs::open_frame_source(fb_path) { + Ok(source) => source, + Err(devfs::OpenError::Missing) => { + eprintln!( + "pagh-terminal: {fb_path} is not present (kernel without the shell-session \ + surface); falling back to the private userspace shell session" + ); + return run_shell_session(args, socket); + } + Err(devfs::OpenError::Failed(reason)) => return fail_with_notice(args, socket, &reason), + }; + let key_sink = match FileInput::open(input_path) { + Ok(sink) => sink, + Err(error) if is_missing_device(&error) => { + eprintln!( + "pagh-terminal: {input_path} is not present (kernel without the shell-session \ + input); falling back to the private userspace shell session" + ); + return run_shell_session(args, socket); + } + Err(error) => return fail_with_notice(args, socket, &format!("{input_path}: {error}")), + }; + let mut frame = match KernelFrame::open(source) { + Ok(frame) => frame, + Err(error) => return fail_with_notice(args, socket, &error.message()), + }; + let info = frame.info(); + eprintln!( + "pagh-terminal: kernel session {}x{} (stride {}, generation {}) on {fb_path}", + info.width, info.height, info.stride, info.generation + ); + + let mut client = SurfaceClient::connect(socket).map_err(|e| format!("{socket}: {e}"))?; + let welcome = client + .handshake("pagh-terminal", Duration::from_secs(5)) + .map_err(|e| format!("handshake: {e}"))?; + eprintln!( + "pagh-terminal: kernel session connected (client {}, screen {}x{})", + welcome.client_id, welcome.screen_width, welcome.screen_height + ); + client + .create_window(args.window_id, args.size.0, args.size.1, &args.title) + .map_err(|e| format!("create_window: {e}"))?; + // Ядро игнорирует SO_RCVTIMEO (см. TERMINAL.md), поэтому окно обязано + // опрашивать сокет неблокирующе и само возвращаться к кадру поверхности. + client + .set_nonblocking(true) + .map_err(|e| format!("nonblocking: {e}"))?; + + let theme = Theme::default(); + let mut width = args.size.0.max(64); + let mut height = args.size.1.max(32); + // ShmSurface: блит пишется прямо в общий mmap, по сокету идут только + // damage-прямоугольники. Для пиксельной поверхности сессии это не + // оптимизация, а разница между «окно оживает» и «3 МиБ на кадр в QEMU-TCG». + let mut shm = match client.enable_shm(width, height) { + Ok(shm) => shm, + Err(error) => { + eprintln!("pagh-terminal: shm unavailable ({error}); full frames"); + None + } + }; + let mut fallback: Option = if shm.is_none() { + Some(Canvas::new(width as usize, height as usize, theme.bg)) + } else { + None + }; + let mut tracker = pagh_ui::damage::DamageTracker::new( + pagh_ui::geom::Rect::new(0, 0, width as i32, height as i32), + pagh_ui::damage::DEFAULT_TILE, + ); + let mut forwarder = KeyForwarder::new(key_sink); + let mut dirty = true; + let mut last_commit = Instant::now(); + let mut input_error_reported = false; + let trace = std::env::var_os("PAGH_TERMINAL_KERNEL_TRACE").is_some(); + + loop { + // 1. Кадр сессии: перерисовываем окно только когда ядро опубликовало + // новый generation — иначе простой не жжёт CPU на блит. + { + let canvas = canvas_mut(&mut shm, &mut fallback); + match frame.draw_if_changed(canvas, &theme) { + Ok(Draw::Drawn { generation }) => { + if trace { + eprintln!("pagh-terminal: kernel frame generation {generation}"); + } + dirty = true; + } + Ok(Draw::Unchanged) => {} + Err(VtFbError::Ended) => { + return end_kernel_session( + &mut client, + &mut shm, + &theme, + width, + height, + ENDED_NOTICE, + ); + } + Err(error) => { + let message = error.message(); + let lines = [ + "[kernel session] the device failed; nothing is simulated instead", + "", + message.as_str(), + "", + "Close this window and relaunch pagh-terminal to retry.", + ]; + let _ = + end_kernel_session(&mut client, &mut shm, &theme, width, height, &lines); + return Err(message); + } + } + } + + // 2. Отправка кадра — не чаще 60 Гц: полный кадр на каждое изменение + // generation не оставляет времени на чтение ввода. + if dirty && last_commit.elapsed() >= Duration::from_millis(16) { + // `retry_full`: кадр не ушёл, нужен полный блит в новый холст. + let mut retry_full = false; + if let Some(shm_frame) = shm.as_mut() { + let damage = tracker.update(&shm_frame.canvas); + match client.commit_shm(shm_frame, damage) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::InvalidData => { + // Поколение поверхности устарело (композитор пересоздал + // memfd): дальше — полный кадр, как legacy-клиент. + if let Some(stale) = shm.take() { + let _ = client.release_shm(&stale); + } + fallback = Some(Canvas::new(width as usize, height as usize, theme.bg)); + tracker.resize(pagh_ui::geom::Rect::new(0, 0, width as i32, height as i32)); + // Новый холст — нужен полный блит, даже если generation + // поверхности не менялась. + retry_full = true; + } + Err(error) => return Err(format!("commit_shm: {error}")), + } + } else if let Some(canvas) = fallback.as_mut() { + commit_blocking(&mut client, canvas)?; + } + if retry_full { + frame.invalidate(); + } + dirty = retry_full; + last_commit = Instant::now(); + } + + // 3. События окна. Клавиши → VT-байты в `/dev/vtinput1`; колесо и + // протяжка не транслируются: scrollback и selection живут в ядре. + // Нулевой дедлайн: ядро игнорирует SO_RCVTIMEO, поэтому «чтение с + // таймаутом» на блокирующем сокете означало бы вечное ожидание, а + // окно обязано возвращаться к кадру поверхности. + for event in client + .poll_events(Duration::ZERO) + .map_err(|e| format!("poll: {e}"))? + { + match event { + Event::Configure(configure) => { + width = configure.width.max(64); + height = configure.height.max(32); + let same_size = shm.as_ref().is_some_and(|frame| { + frame.canvas.width == width as usize + && frame.canvas.height == height as usize + }); + if same_size { + frame.invalidate(); + dirty = true; + continue; + } + let resized = match shm.as_mut() { + Some(frame) => client.resize_shm(frame, width, height).unwrap_or(false), + None => false, + }; + if resized { + tracker.resize(pagh_ui::geom::Rect::new(0, 0, width as i32, height as i32)); + } else { + if let Some(stale) = shm.take() { + let _ = client.release_shm(&stale); + } + fallback = Some(Canvas::new(width as usize, height as usize, theme.bg)); + tracker.resize(pagh_ui::geom::Rect::new(0, 0, width as i32, height as i32)); + } + // Масштаб под новый content rect меняется — полный блит. + frame.invalidate(); + dirty = true; + } + Event::ShmRelease { + window_id, + generation, + } => { + if window_id == args.window_id + && shm + .as_ref() + .is_some_and(|frame| frame.generation == generation) + { + if let Some(stale) = shm.take() { + let _ = client.release_shm(&stale); + } + fallback = Some(Canvas::new(width as usize, height as usize, theme.bg)); + tracker.resize(pagh_ui::geom::Rect::new(0, 0, width as i32, height as i32)); + frame.invalidate(); + dirty = true; + } + } + Event::ShmReady { .. } => {} + Event::Input(InputEvent::Key { + code, + pressed, + modifiers, + }) => match forwarder.handle_key(code, pressed, modifiers) { + Ok(_) => {} + Err(error) if is_session_end(&error) => { + // Сессия закончилась между кадром и нажатием: следующий + // опрос поверхности вернёт ENODEV и закроет окно честно. + if !input_error_reported { + eprintln!( + "pagh-terminal: session ended while forwarding a key ({error})" + ); + input_error_reported = true; + } + } + Err(error) => { + if !input_error_reported { + eprintln!("pagh-terminal: cannot write {input_path}: {error}"); + input_error_reported = true; + } + } + }, + Event::Focus { .. } => { + // Курсор рисует ядро в пикселях: подсветка фокуса здесь не наша. + } + Event::Input(InputEvent::Axis { .. }) | Event::Input(InputEvent::Button { .. }) => { + // Скроллбек и selection принадлежат сессии ядра; у окна нет + // доступа к её сетке, поэтому событие честно игнорируется. + } + Event::Input(InputEvent::Motion { .. }) => {} + Event::Close { reason, .. } => { + eprintln!( + "pagh-terminal: server closed the window ({})", + close_name(reason) + ); + return Ok(()); + } + Event::Error { code, message } => { + eprintln!( + "pagh-terminal: server error {} ({}): {}", + error_name(code), + code, + message + ); + } + Event::Ping(_) | Event::Pong(_) => {} + } + } + + // Простой: не крутим CPU, но и не спим дольше одного кадра. Сессия + // ядра флашит generation на каждую операцию shell'а, поэтому 6 мс — + // это ≤ ~160 проверок ioctl/с, дешевле любой перерисовки. + std::thread::sleep(Duration::from_millis(6)); + } +} + +/// Что показать в окне, когда `exit` в сессии ядра завершил её (`ENODEV`). +const ENDED_NOTICE: &[&str] = &[ + "[kernel session] the shell session has ended.", + "", + "The kernel starts a fresh session on the next open, so relaunch", + "pagh-terminal to reconnect. Nothing is simulated in the meantime.", +]; + +/// Получить текущий холст окна (общий mmap или локальный fallback). +fn canvas_mut<'a>( + shm: &'a mut Option, + fallback: &'a mut Option, +) -> &'a mut Canvas { + match shm.as_mut() { + Some(frame) => &mut frame.canvas, + None => fallback + .as_mut() + .expect("fallback canvas exists whenever shm is absent"), + } +} + +/// Финальный кадр с честным сообщением: отдать его окну и закрыть клиент. +/// +/// ShmSurface отпускается, кадр уходит полным `commit` — сообщение должно +/// дойти даже если memfd уже невалиден. +fn end_kernel_session( + client: &mut SurfaceClient, + shm: &mut Option, + theme: &Theme, + width: u32, + height: u32, + lines: &[&str], +) -> Result<(), String> { + show_notice(client, shm, theme, width, height, lines)?; + let _ = client.close(); + eprintln!("pagh-terminal: kernel session ended (the shell exited); window closed"); + Ok(()) +} + +/// Нарисовать сообщение клиента в окне и подержать его `NOTICE_HOLD`. +fn show_notice( + client: &mut SurfaceClient, + shm: &mut Option, + theme: &Theme, + width: u32, + height: u32, + lines: &[&str], +) -> Result<(), String> { + if let Some(stale) = shm.take() { + let _ = client.release_shm(&stale); + } + let mut canvas = Canvas::new(width.max(64) as usize, height.max(32) as usize, theme.bg); + render_notice(&mut canvas, theme, lines); + commit_blocking(client, &canvas)?; + std::thread::sleep(NOTICE_HOLD); + Ok(()) +} + +/// Устройство есть, но работать с ним нельзя: честное сообщение в окне. +/// +/// Окно создаётся только чтобы сказать правду (запуск из шелла без дисплея +/// просто получит ошибку в stderr). Никакого отката в демо-шелл: пользователь +/// должен видеть, что сессии ядра нет. +fn fail_with_notice(args: &Args, socket: &str, reason: &str) -> Result<(), String> { + eprintln!("pagh-terminal: kernel session unavailable: {reason}"); + let mut client = SurfaceClient::connect(socket).map_err(|e| format!("{socket}: {e}"))?; + client + .handshake("pagh-terminal", Duration::from_secs(5)) + .map_err(|e| format!("handshake: {e}"))?; + client + .create_window(args.window_id, args.size.0, args.size.1, &args.title) + .map_err(|e| format!("create_window: {e}"))?; + let theme = Theme::default(); + let lines = [ + "[kernel session] the kernel shell-session devices are not usable", + "", + reason, + "", + "The window renders the kernel's shell session over", + "/dev/vtfb1 + /dev/vtinput1; it does not simulate commands.", + ]; + let mut no_shm = None; + show_notice( + &mut client, + &mut no_shm, + &theme, + args.size.0, + args.size.1, + &lines, + )?; + let _ = client.close(); + Err(reason.to_string()) +} + fn render_frame(screen: &pagh_terminal::Screen, theme: &Theme, width: u32, height: u32) -> Canvas { let width = width.max(1) as usize; let height = height.max(1) as usize; @@ -936,7 +1391,8 @@ fn parse_args>(mut args: I) -> Result { "--headless" => out.headless = true, "--socket" => out.socket = Some(next_value(&mut args, "--socket")?), "--vt" => out.vt = Some(next_value(&mut args, "--vt")?), - "--vt-input" => out.vt_input = next_value(&mut args, "--vt-input")?, + "--vt-input" => out.vt_input = Some(next_value(&mut args, "--vt-input")?), + "--vt-fb" => out.vt_fb = next_value(&mut args, "--vt-fb")?, "--size" => out.size = parse_size(&next_value(&mut args, "--size")?)?, "--cols" => out.cols = Some(parse_usize(&next_value(&mut args, "--cols")?)?), "--rows" => out.rows = Some(parse_usize(&next_value(&mut args, "--rows")?)?), @@ -962,6 +1418,8 @@ fn parse_args>(mut args: I) -> Result { out.shell_cmd = Some(PathBuf::from(next_value(&mut args, "--shell-cmd")?)) } "--mirror-vt" => out.mirror_vt = true, + "--pipe-shell" => out.pipe_shell = true, + "--demo-shell" => out.demo_shell = true, "--help" | "-h" => out.help = true, "--version" | "-V" => out.version = true, other => return Err(format!("unknown argument {other:?}; try --help")), @@ -1022,11 +1480,25 @@ USAGE: pagh-terminal --headless [--demo NAME|--script FILE] [--cols N --rows N] [--out FILE.png] [--print|--print-full] [--window|--no-window] [--scroll N] [--select R1,C1:R2,C2] [--dump-selection] - pagh-terminal --socket PATH [--size WxH] [--title TITLE] [--feed FILE] + pagh-terminal --socket PATH [--size WxH] [--title TITLE] + [--vt-fb /dev/vtfb1] [--vt-input /dev/vtinput1] pagh-terminal --vt /dev/vtconsole0 [--socket PATH] [--vt-input /dev/vtinput] [--mirror-vt] pagh-terminal --screenshots DIR +WINDOW (default with --socket): KERNEL SHELL SESSION + The window attaches to the kernel's own shell session: it blits the pixels of + /dev/vtfb1 into the window and forwards window keys as VT bytes to + /dev/vtinput1. Commands (df, ps, ppkg, lxrun, disk, nano, history, line + editing, scrollback) are the kernel's — the client renders and forwards input + only, and simulates nothing. + --vt-fb PATH session pixel surface (default /dev/vtfb1) + --vt-input PATH session input device (default /dev/vtinput1) + If the devices are missing (kernel without the session surface) the window + says so on stderr and falls back to the private userspace shell session. If + the devices exist but fail, the window shows the honest error and exits; it + never pretends to be a shell. + HEADLESS: --demo NAME 01-welcome, 02-colors, 03-scrollback, 04-unicode --script FILE raw terminal output (escape sequences allowed) @@ -1038,18 +1510,29 @@ HEADLESS: LIVE: --socket PATH AF_UNIX control socket of pagh-desktop --size WxH initial window content size (default 900x600) - --feed FILE preload terminal output into the demo shell --window-id N client-chosen window id (default 101) - --vt PATH kernel VT shared surface (ABI v1): with --socket the window - now starts its own shell session; without --socket this - prints a snapshot (diagnostics) - --vt-input PATH where the VT mirror writes input bytes (default /dev/vtinput) - --mirror-vt keep mirroring the boot VT in the window instead of starting - the session (diagnostics; the boot VT is held by lxrun) + --feed FILE preload terminal output into the demo shell + --demo-shell explicit demo-shell window (screenshots, A/B comparison) + --pipe-shell explicit userspace shell over two pipes (fallback/test mode; + minimal built-in commands, not the kernel shell) + --vt PATH kernel VT console shared surface (ABI v1): with --socket the + window mirrors the boot VT; without --socket it prints one + snapshot (diagnostics) + --vt-input PATH input device override for --vt/--mirror-vt (default + /dev/vtinput) and for the kernel session (default + /dev/vtinput1) + --mirror-vt mirror the boot VT in the window (diagnostics; the boot VT is + held by lxrun). Without --vt the path defaults to + /dev/vtconsole0 --shell-child internal: run as the session's shell process (pipes) --shell-cmd PATH child program for the session (default: this binary with --shell-child; use a real shell when the image has one) +NOT IN THIS STAGE (honest gaps): no PTY/termios, no TIOCGWINSZ/SIGWINCH (the +kernel owns the shell size), no terminal job control, and the pixel surface +carries no DEC private modes — arrow keys are always sent in normal mode. One +kernel session per window; scrollback and selection stay in the kernel. + SCREENSHOTS: --screenshots DIR regenerate the committed demo PNG fixtures diff --git a/rust-apps/pagh-terminal/src/bin/pagh-terminal/devfs.rs b/rust-apps/pagh-terminal/src/bin/pagh-terminal/devfs.rs new file mode 100644 index 00000000..0183c0c6 --- /dev/null +++ b/rust-apps/pagh-terminal/src/bin/pagh-terminal/devfs.rs @@ -0,0 +1,174 @@ +//! Реальные устройства режима kernel-session: `/dev/vtfb1` + `/dev/vtinput1`. +//! +//! Весь `unsafe` крейта сосредоточен здесь: `lib.rs` объявляет +//! `#![forbid(unsafe_code)]`, а `mmap`/`ioctl`/`munmap` безопасными не бывают. +//! Слой намеренно тонкий — он умеет ровно три вещи: спросить геометрию через +//! ioctl `0x4700`, отобразить пиксели `mmap(PROT_READ, MAP_SHARED)` и, если +//! поверхность не mmap'ится, откатиться на `read()`-снимки +//! (`kernelsession::ReadFrameSource`, он же покрыт host-тестами). +//! +//! Вся логика (валидация заголовка, `generation`-гейт, блит, сообщения об +//! ошибках) живёт в lib и проверяется без устройств: на хосте `/dev/vtfb1` нет. + +use std::ffi::{c_int, c_ulong, c_void}; +use std::fs::File; +use std::io; +use std::os::unix::io::AsRawFd; + +use pagh_terminal::kernelsession::{ + FrameSource, ReadFrameSource, VtFbError, VtFbInfo, INFO_LEN, VTFB_IOCTL_GET_INFO, +}; + +/// `PROT_READ`. +const PROT_READ: c_int = 0x1; +/// `MAP_SHARED` — единственный честный вариант для поверхности ядра: копия не +/// нужна, ядро владеет записью. +const MAP_SHARED: c_int = 0x1; + +extern "C" { + fn ioctl(fd: c_int, request: c_ulong, arg: *mut c_void) -> c_int; + fn mmap( + addr: *mut c_void, + len: usize, + prot: c_int, + flags: c_int, + fd: c_int, + offset: i64, + ) -> *mut c_void; + fn munmap(addr: *mut c_void, len: usize) -> c_int; +} + +/// Почему устройство не открылось. +pub enum OpenError { + /// Устройства нет в системе (`ENOENT`): ядро без `/dev/vtfb1`. + Missing, + /// Устройство есть, но работать с ним нельзя — честный текст для окна. + Failed(String), +} + +/// Открыть пиксельную поверхность сессии: `mmap` основной путь, `read()` fallback. +/// +/// `mmap`-отказ (не mmap-устройство, `ENOSYS`/`ENOTTY`/`EINVAL`) не является +/// фатальным: контракт разрешает `read()`-снимки, поэтому клиент деградирует на +/// них и говорит об этом в stderr. Отсутствие самого устройства — не деградация, +/// а [`OpenError::Missing`], по которому вызывающий откатывается на pipe-сессию. +pub fn open_frame_source(path: &str) -> Result, OpenError> { + let file = match File::open(path) { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Err(OpenError::Missing), + Err(error) => { + return Err(OpenError::Failed(format!( + "{path}: {error} (the kernel shell-session surface is not readable by this process)" + ))) + } + }; + match MmapSurface::new(file) { + Ok(surface) => Ok(Box::new(surface)), + Err(reason) => { + eprintln!( + "pagh-terminal: mmap of {path} unavailable ({reason}); falling back to read() snapshots" + ); + match ReadFrameSource::open(path) { + Ok(source) => Ok(Box::new(source)), + Err(error) => Err(OpenError::Failed(format!("{path}: {}", error.message()))), + } + } + } +} + +/// Пиксельная поверхность сессии через `mmap`. +struct MmapSurface { + /// Держим fd открытым: закрытие `fd` при живом отображении — законно, но + /// повторный ioctl `generation` делается по этому же fd. + file: File, + base: *mut u8, + len: usize, + info: VtFbInfo, +} + +impl MmapSurface { + fn new(file: File) -> Result { + let info = query_info(&file) + .map_err(|error| format!("ioctl 0x{VTFB_IOCTL_GET_INFO:04x}: {error}"))?; + let len = info.pixels_len(); + if len == 0 { + return Err("the kernel reported a zero-byte framebuffer".to_string()); + } + // SAFETY: PROT_READ+MAP_SHARED на fd, который живёт в `file`; offset 0 — + // контракт поверхности. При провале ядро возвращает MAP_FAILED, который + // проверяется до любого чтения. + let base = unsafe { + mmap( + std::ptr::null_mut(), + len, + PROT_READ, + MAP_SHARED, + file.as_raw_fd(), + 0, + ) + }; + if base as isize == -1 { + return Err(format!( + "mmap({len} bytes) failed: {}", + io::Error::last_os_error() + )); + } + Ok(MmapSurface { + file, + base: base as *mut u8, + len, + info, + }) + } +} + +impl FrameSource for MmapSurface { + fn poll(&mut self) -> Result { + let info = query_info(&self.file)?; + if info.pixels_len() > self.len { + // Разрешение kernel-VT сменилось на живой сессии — это контрактный + // разрыв, а не повод читать за отображением. + return Err(VtFbError::BadInfo( + "framebuffer grew past the mapping (relaunch the window)", + )); + } + self.info = info; + Ok(info) + } + + fn with_pixels(&mut self, f: &mut dyn FnMut(&[u8])) -> Result<(), VtFbError> { + let len = self.info.pixels_len().min(self.len); + // SAFETY: `base..base+len` — отображение, созданное в `new` и живое до + // `Drop`; ядро пишет туда, мы только читаем (PROT_READ). + let pixels = unsafe { std::slice::from_raw_parts(self.base, len) }; + f(pixels); + Ok(()) + } +} + +impl Drop for MmapSurface { + fn drop(&mut self) { + // SAFETY: отображение создано `mmap` в `new` и ещё не снималось. + unsafe { + munmap(self.base as *mut c_void, self.len); + } + } +} + +/// ioctl `VTFBIOGET_INFO` → [`VtFbInfo`]. +fn query_info(file: &File) -> Result { + let mut header = [0u8; INFO_LEN]; + // SAFETY: буфер ровно 24 байта — столько ядро пишет по контракту; ioctl + // получает живой fd из `file`. + let rc = unsafe { + ioctl( + file.as_raw_fd(), + VTFB_IOCTL_GET_INFO as c_ulong, + header.as_mut_ptr() as *mut c_void, + ) + }; + if rc < 0 { + return Err(VtFbError::from(io::Error::last_os_error())); + } + VtFbInfo::parse(&header) +} diff --git a/rust-apps/pagh-terminal/src/kernelsession.rs b/rust-apps/pagh-terminal/src/kernelsession.rs new file mode 100644 index 00000000..7bb7f844 --- /dev/null +++ b/rust-apps/pagh-terminal/src/kernelsession.rs @@ -0,0 +1,778 @@ +//! Kernel shell-session surface: `/dev/vtfb1` (pixels) + `/dev/vtinput1` (keys). +//! +//! Это **основной** режим окна терминала в desktop B: окно не запускает +//! собственный userspace-shell и не имитирует команды. Ядро владеет второй +//! shell-сессией (`pf`, `ps`, `ppkg`, `lxrun`, `disk`, `nano`, history…), рисует +//! её в собственную пиксельную поверхность, а клиент только блитит пиксели в +//! окно и передаёт ввод обратно. Полный набор команд, эхо, редактирование строки +//! и scrollback делает ядро — здесь нет ни одной команды и ни одного байта +//! «притворства». +//! +//! Контракт устройств (зафиксирован координатором; kernel-side реализация идёт +//! параллельно, live-интеграцию делает координатор): +//! +//! ```text +//! /dev/vtfb1 (read-only) +//! ioctl 0x4700 (VTFBIOGET_INFO) -> 24 байта LE: +//! u32 width, u32 height, u32 stride, u32 bpp(=32), u64 generation +//! mmap(NULL, stride*height, PROT_READ, MAP_SHARED, fd, 0) -> пиксели 32bpp XRGB +//! read() fallback: те же 24 байта заголовка + пиксели +//! generation растёт на каждый flush сессии; ENODEV после `exit` в сессии +//! (первый open любого из двух устройств спавнит сессию ядра заново) +//! +//! /dev/vtinput1 (write-only) +//! VT-байты клавиатуры — тот же формат, что у `/dev/vtinput` +//! (`keys::encode_key`, см. `vtconsole::send_input`) +//! ``` +//! +//! Почему lib, а не bin: `lib.rs` объявляет `#![forbid(unsafe_code)]`, а mmap и +//! ioctl — unsafe. Поэтому здесь живёт вся **безопасная** логика (разбор +//! заголовка, валидация геометрии, решение о перерисовке по `generation`, блит, +//! разбор ошибок, кодирование клавиш), а неустранимо-небезопасный слой +//! (`ioctl`/`mmap`/`munmap`) — в `src/bin/pagh-terminal/devfs.rs`. Благодаря +//! этому режим целиком прогоняется host-тестами на mock-устройстве: на хосте +//! `/dev/vtfb1` нет и быть не может. +//! +//! Честные границы v1 (подробнее — `TERMINAL.md`): +//! +//! * одно окно = одна сессия ядра; второй клиент получает ту же поверхность; +//! * нет PTY/termios/job-control: `Ctrl+C`/`Ctrl+Z` — просто байты в +//! `/dev/vtinput1`, а `TIOCGWINSZ`/SIGWINCH неоткуда взять (размер знает +//! только ядро); +//! * клиент не наблюдает DEC-режимы (пиксели не говорят, хочет ли сессия +//! application-cursor keys), поэтому стрелки кодируются в normal-режиме +//! (`KeyModes::default()`), как kernel-shell и ожидает; +//! * scrollback и selection остаются в ядре: колесо и протяжка мышью в окно не +//! транслируются; +//! * при downscale текст режется (nearest neighbour, без фильтра) — выбор +//! политики см. [`fit_placement`]. + +use std::fs::{File, OpenOptions}; +use std::io::{self, Read, Write}; +use std::os::unix::fs::FileExt; +use std::path::{Path, PathBuf}; + +use crate::font::{CELL_H, CELL_W}; +use crate::keys::{self, KeyModes}; +use crate::render::{render_screen_into, Canvas, RenderOptions, Theme, VIEWPORT_PADDING}; +use crate::Terminal; + +/// `VTFBIOGET_INFO` — ioctl, отдающий [`VtFbInfo`] (24 байта little-endian). +pub const VTFB_IOCTL_GET_INFO: u32 = 0x4700; +/// Размер структуры [`VtFbInfo`] на проводе. +pub const INFO_LEN: usize = 24; +/// Единственный поддерживаемый формат пикселя: 32bpp XRGB (младший байт — B). +pub const BPP: u32 = 32; +/// Геометрический предел: защита от мусорного ioctl-ответа, до аллокаций. +pub const MAX_DIM: u32 = 8192; +/// Предел одного кадра в байтах (32 МиБ ≈ 8192×1024×4) — до mmap/чтения. +pub const MAX_FRAME_BYTES: usize = 32 * 1024 * 1024; + +/// Значение errno `ENODEV`: сессия ядра завершилась (`exit` в shell'е). +const ENODEV: i32 = 19; + +/// Устройства нет в системе (старое ядро без `/dev/vtfb1`). +pub fn is_missing_device(error: &io::Error) -> bool { + error.kind() == io::ErrorKind::NotFound +} + +/// `ENODEV`: сессия ядра завершилась; повторный `open` спавнит новую. +pub fn is_session_end(error: &io::Error) -> bool { + error.raw_os_error() == Some(ENODEV) +} + +/// Заголовок поверхности сессии ядра (ioctl-ответ или префикс `read()`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct VtFbInfo { + pub width: u32, + pub height: u32, + /// Байт на строку; ядро может выравнивать строки, поэтому `>= width*4`. + pub stride: u32, + pub bpp: u32, + /// Растёт на каждый flush сессии — единственный сигнал «кадр изменился». + pub generation: u64, +} + +impl VtFbInfo { + /// Разобрать 24 байта little-endian и провалидировать геометрию. + /// + /// Валидация стоит **до** любого `mmap`/чтения пикселей: мусорный ответ + /// ioctl не должен превращаться в гигантскую аллокацию или выход за + /// отображение. + pub fn parse(bytes: &[u8]) -> Result { + if bytes.len() < INFO_LEN { + return Err(VtFbError::ShortRead { + need: INFO_LEN, + have: bytes.len(), + }); + } + let info = VtFbInfo { + width: read_u32(bytes, 0), + height: read_u32(bytes, 4), + stride: read_u32(bytes, 8), + bpp: read_u32(bytes, 12), + generation: read_u64(bytes, 16), + }; + info.validate()?; + Ok(info) + } + + /// Обратное к [`VtFbInfo::parse`] — для mock-устройств и тестовых файлов. + pub fn encode(self) -> [u8; INFO_LEN] { + let mut bytes = [0u8; INFO_LEN]; + bytes[0..4].copy_from_slice(&self.width.to_le_bytes()); + bytes[4..8].copy_from_slice(&self.height.to_le_bytes()); + bytes[8..12].copy_from_slice(&self.stride.to_le_bytes()); + bytes[12..16].copy_from_slice(&self.bpp.to_le_bytes()); + bytes[16..24].copy_from_slice(&self.generation.to_le_bytes()); + bytes + } + + /// Проверить контракт: 32bpp, непустые размеры, `stride >= width*4`, пределы. + pub fn validate(&self) -> Result<(), VtFbError> { + if self.bpp != BPP { + return Err(VtFbError::BadInfo("bpp must be 32")); + } + if self.width == 0 || self.height == 0 { + return Err(VtFbError::BadInfo("width/height must be non-zero")); + } + if self.width > MAX_DIM || self.height > MAX_DIM { + return Err(VtFbError::BadInfo("framebuffer exceeds 8192x8192")); + } + let min_stride = (self.width as u64) * 4; + if (self.stride as u64) < min_stride { + return Err(VtFbError::BadInfo("stride is smaller than width * 4")); + } + if (self.stride as u64) > (MAX_DIM as u64) * 4 { + return Err(VtFbError::BadInfo("stride exceeds 8192 * 4")); + } + if self.pixels_len() > MAX_FRAME_BYTES { + return Err(VtFbError::TooLarge); + } + Ok(()) + } + + /// Байт в одном кадре: `stride * height`. + pub fn pixels_len(&self) -> usize { + (self.stride as usize).saturating_mul(self.height as usize) + } +} + +/// Ошибка поверхности/сессии. `Ended` — не сбой, а событие: shell завершился. +#[derive(Debug)] +pub enum VtFbError { + Io(io::Error), + /// `ENODEV`: сессия ядра завершилась; следующий open — новая сессия. + Ended, + BadInfo(&'static str), + ShortRead { + need: usize, + have: usize, + }, + TooLarge, +} + +impl VtFbError { + pub fn is_ended(&self) -> bool { + matches!(self, VtFbError::Ended) + } + + /// Честный текст для окна и stderr: что именно случилось и что делать. + pub fn message(&self) -> String { + match self { + VtFbError::Io(error) => format!("device I/O error: {error}"), + VtFbError::Ended => { + "the kernel shell session ended (ENODEV). The kernel starts a new one on the \ + next open — relaunch the window to reconnect." + .to_string() + } + VtFbError::BadInfo(what) => format!("kernel framebuffer contract violation: {what}"), + VtFbError::ShortRead { need, have } => { + format!("short frame from the kernel: need {need} bytes, got {have}") + } + VtFbError::TooLarge => "kernel framebuffer exceeds the supported size".to_string(), + } + } +} + +impl std::fmt::Display for VtFbError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.message()) + } +} + +impl std::error::Error for VtFbError {} + +impl From for VtFbError { + fn from(error: io::Error) -> VtFbError { + if is_session_end(&error) { + VtFbError::Ended + } else { + VtFbError::Io(error) + } + } +} + +/// Источник кадров сессии ядра: `mmap`-поверхность или `read()`-fallback. +/// +/// Трейт сознательно двухшаговый, как и контракт: `poll()` дёшев (один ioctl +/// или 24 байта `pread`) и отвечает «изменился ли кадр», а пиксели читаются +/// только когда generation действительно вырос. +pub trait FrameSource { + /// Текущая геометрия и generation. + fn poll(&mut self) -> Result; + /// Отдать кадр (ровно `stride * height` байт) замыканию. + /// + /// Замыкание, а не возвращаемый `&[u8]`: у mmap-источника нет владеющего + /// буфера, а у read-fallback он есть, и оба обязаны выглядеть одинаково для + /// безопасного кода lib-крейта (`#![forbid(unsafe_code)]`). + fn with_pixels(&mut self, f: &mut dyn FnMut(&[u8])) -> Result<(), VtFbError>; +} + +/// Приёмник VT-байтов ввода (в бою — `/dev/vtinput1`). +pub trait InputSink { + fn send(&mut self, bytes: &[u8]) -> io::Result<()>; +} + +impl FrameSource for Box { + fn poll(&mut self) -> Result { + (**self).poll() + } + + fn with_pixels(&mut self, f: &mut dyn FnMut(&[u8])) -> Result<(), VtFbError> { + (**self).with_pixels(f) + } +} + +/// `read()`-fallback поверхности: `pread` заголовка + пикселей. +/// +/// Реализация в lib, а не в bin, намеренно: она полностью безопасна (std +/// `FileExt::read_at`), поэтому host-тест гоняет её на обычном файле — без +/// `/dev/vtfb1` и без ядра. Именно этот путь используют ядра, где mmap +/// поверхности не поддержан, и он же документирован в `TERMINAL.md`. +pub struct ReadFrameSource { + file: File, + path: PathBuf, + info: VtFbInfo, + buffer: Vec, +} + +impl ReadFrameSource { + pub fn open(path: impl AsRef) -> Result { + let path = path.as_ref().to_path_buf(); + let file = File::open(&path)?; + let mut header = [0u8; INFO_LEN]; + read_exact_at(&file, &mut header, 0)?; + let info = VtFbInfo::parse(&header)?; + Ok(ReadFrameSource { + file, + path, + info, + buffer: vec![0; info.pixels_len()], + }) + } + + pub fn path(&self) -> &Path { + &self.path + } +} + +impl FrameSource for ReadFrameSource { + fn poll(&mut self) -> Result { + let mut header = [0u8; INFO_LEN]; + read_exact_at(&self.file, &mut header, 0)?; + self.info = VtFbInfo::parse(&header)?; + Ok(self.info) + } + + fn with_pixels(&mut self, f: &mut dyn FnMut(&[u8])) -> Result<(), VtFbError> { + // Один связный снимок: заголовок и пиксели читаются из offset 0 в + // одном проходе, поэтому geometry/generation принадлежат тем же + // пикселям, которые уйдут в кадр. + let mut header = [0u8; INFO_LEN]; + read_exact_at(&self.file, &mut header, 0)?; + let info = VtFbInfo::parse(&header)?; + let len = info.pixels_len(); + if len > MAX_FRAME_BYTES { + return Err(VtFbError::TooLarge); + } + self.buffer.resize(len, 0); + read_exact_at(&self.file, &mut self.buffer, INFO_LEN as u64)?; + self.info = info; + f(&self.buffer); + Ok(()) + } +} + +/// `InputSink` поверх обычного файла (`/dev/vtinput1`). +pub struct FileInput { + file: File, +} + +impl FileInput { + pub fn open(path: impl AsRef) -> io::Result { + let file = OpenOptions::new().write(true).open(path)?; + Ok(FileInput { file }) + } +} + +impl InputSink for FileInput { + fn send(&mut self, bytes: &[u8]) -> io::Result<()> { + // Без flush: это символьное устройство, `write` уже отдал байты ядру. + self.file.write_all(bytes) + } +} + +/// Раскладка кадра сессии внутри окна: `dst`-прямоугольник и его смещение. +/// +/// Политика (одна, документированная, без «умных» эвристик): +/// +/// * окно **не меньше** поверхности — блит 1:1 по центру, без ресемплинга +/// (пиксель в пиксель: текст ядра не мылится); +/// * окно **меньше** — downscale с сохранением пропорций (nearest neighbour, +/// целочисленная арифметика) и центрирование; края заливаются фоном темы; +/// * **обрезки нет** никогда: вся поверхность сессии видна целиком. Обрезка +/// спрятала бы часть вывода shell'а (ячейки 8×18 px, окно на 900×600 почти +/// всегда меньше типичного kernel-fb), а потерянный вывод хуже, чем +/// потерянная строка пикселей; +/// * **апскейла нет**: увеличение окна не растягивает кадр до мыла, а +/// показывает его 1:1 по центру. +pub fn fit_placement( + src_w: usize, + src_h: usize, + dst_w: usize, + dst_h: usize, +) -> Option { + if src_w == 0 || src_h == 0 || dst_w == 0 || dst_h == 0 { + return None; + } + let (width, height) = if src_w <= dst_w && src_h <= dst_h { + (src_w, src_h) + } else if (src_w as u64) * (dst_h as u64) >= (src_h as u64) * (dst_w as u64) { + // Поверхность «шире» окна: упираемся в ширину. + let height = ((src_h as u64 * dst_w as u64) / src_w as u64) as usize; + (dst_w, height.clamp(1, dst_h)) + } else { + let width = ((src_w as u64 * dst_h as u64) / src_h as u64) as usize; + (width.clamp(1, dst_w), dst_h) + }; + Some(FitPlacement { + x: (dst_w - width) / 2, + y: (dst_h - height) / 2, + width, + height, + }) +} + +/// Прямоугольник вывода кадра в окне (см. [`fit_placement`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FitPlacement { + pub x: usize, + pub y: usize, + pub width: usize, + pub height: usize, +} + +/// Блит XRGB-пикселей ядра в RGBA-канву окна. +/// +/// Байты в памяти — `B, G, R, X` (XRGB8888 little-endian, как формат 1 PDP/1). +/// Источник короче объявленного `stride * height` — честная ошибка +/// [`VtFbError::ShortRead`], а не «нарисуем что-нибудь». +pub fn blit_xrgb( + src: &[u8], + info: &VtFbInfo, + canvas: &mut Canvas, + place: &FitPlacement, +) -> Result<(), VtFbError> { + let src_w = info.width as usize; + let src_h = info.height as usize; + let stride = info.stride as usize; + if place.width == 0 || place.height == 0 { + return Ok(()); + } + for dy in 0..place.height { + let sy = dy * src_h / place.height; + let row = sy.saturating_mul(stride); + for dx in 0..place.width { + let sx = dx * src_w / place.width; + let index = row + sx * 4; + let Some(pixel) = src.get(index..index + 4) else { + return Err(VtFbError::ShortRead { + need: row + sx * 4 + 4, + have: src.len(), + }); + }; + canvas.set_pixel_rgba( + place.x + dx, + place.y + dy, + [pixel[2], pixel[1], pixel[0], 255], + ); + } + } + Ok(()) +} + +/// Результат [`KernelFrame::draw_if_changed`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Draw { + /// `generation` не менялась — кадр не трогали. + Unchanged, + /// Кадр перерисован; `generation` — та, что попала в окно. + Drawn { generation: u64 }, +} + +/// Драйвер кадра сессии: `generation`-гейт, блит, полная перерисовка при +/// повреждении/ресайзе. +/// +/// Контракт ядра не даёт seqlock (в отличие от `/dev/vtconsole0`), поэтому +/// кадр может быть «порван» flush'ем посередине блита. Реакция — полный блит +/// на следующем изменении `generation`: следующий кадр непротиворечив целиком, +/// потому что сессия публикует его атомарно по `generation`. Никаких +/// частичных damage от ядра v1 не приходит. +pub struct KernelFrame { + source: S, + info: VtFbInfo, + last_generation: Option, + full: bool, +} + +impl KernelFrame { + /// Открыть драйвер: первый `poll()` валидирует геометрию до первого блита. + pub fn open(mut source: S) -> Result, VtFbError> { + let info = source.poll()?; + Ok(KernelFrame { + source, + info, + last_generation: None, + full: true, + }) + } + + pub fn info(&self) -> VtFbInfo { + self.info + } + + /// Забыть generation: следующий кадр блитится полностью (ресайз окна, + /// пересоздание поверхности, возврат фокуса). + pub fn invalidate(&mut self) { + self.full = true; + } + + /// Перерисовать окно, если ядро опубликовало новый кадр. + pub fn draw_if_changed( + &mut self, + canvas: &mut Canvas, + theme: &Theme, + ) -> Result { + let info = self.source.poll()?; + if !self.full && Some(info.generation) == self.last_generation && info == self.info { + return Ok(Draw::Unchanged); + } + let Some(place) = fit_placement( + info.width as usize, + info.height as usize, + canvas.width, + canvas.height, + ) else { + return Ok(Draw::Unchanged); + }; + canvas.fill(theme.bg); + let need = info.pixels_len(); + let mut shortfall = None; + self.source.with_pixels(&mut |pixels| { + if pixels.len() < need { + shortfall = Some(pixels.len()); + return; + } + if let Err(error) = blit_xrgb(pixels, &info, canvas, &place) { + shortfall = Some(match error { + VtFbError::ShortRead { have, .. } => have, + _ => 0, + }); + } + })?; + if let Some(have) = shortfall { + return Err(VtFbError::ShortRead { need, have }); + } + self.info = info; + self.last_generation = Some(info.generation); + self.full = false; + Ok(Draw::Drawn { + generation: info.generation, + }) + } +} + +/// Кодирование клавиши окна в VT-байты для `/dev/vtinput1`. +/// +/// Режимы — `KeyModes::default()`: поверхность сессии пиксельная, DEC-режимы +/// (`?1` application cursor, bracketed paste, mouse) из неё не наблюдаемы. +/// Kernel-shell не включает application-cursor, поэтому normal-стрелки — +/// корректный и единственно возможный выбор v1; ограничение названо в +/// `TERMINAL.md`. +pub fn encode_key_bytes(code: u32, pressed: bool, modifiers: u32) -> Vec { + keys::encode_key(code, pressed, modifiers, &KeyModes::default()) +} + +/// Пересылка клавиш окна в приёмник ввода. +pub struct KeyForwarder { + sink: S, + modes: KeyModes, +} + +impl KeyForwarder { + pub fn new(sink: S) -> KeyForwarder { + KeyForwarder { + sink, + modes: KeyModes::default(), + } + } + + /// Отправить одно событие клавиши; возвращает число записанных байт. + /// + /// Release и чистые модификаторы кодируются в пустой вектор и не пишут + /// ничего: пустой `write` на устройстве ввода — лишний сисколл и + /// (теоретически) ложное «событие» для ядра. + pub fn handle_key(&mut self, code: u32, pressed: bool, modifiers: u32) -> io::Result { + let bytes = keys::encode_key(code, pressed, modifiers, &self.modes); + if bytes.is_empty() { + return Ok(0); + } + self.sink.send(&bytes)?; + Ok(bytes.len()) + } + + pub fn sink(&self) -> &S { + &self.sink + } +} + +/// Нарисовать честное сообщение (ошибка устройства, конец сессии) в окне. +/// +/// Окно режима kernel-session — пиксельная поверхность, поэтому «напечатать +/// текст» можно только собственным рендерером: собираем обычный `Terminal`, +/// кормим строки и рисуем его в канву. Это не имитация shell'а — это +/// сообщение клиента о том, что сессии больше нет. +pub fn render_notice(canvas: &mut Canvas, theme: &Theme, lines: &[&str]) { + let pad = VIEWPORT_PADDING * 2; + let cols = (canvas.width.saturating_sub(pad) / CELL_W).max(8); + let rows = (canvas.height.saturating_sub(pad) / CELL_H).max(2); + let mut terminal = Terminal::new(cols, rows); + terminal.screen.set_default_colors(theme.fg, theme.bg); + for line in lines { + terminal.feed_str(line); + terminal.feed_str("\r\n"); + } + canvas.fill(theme.bg); + render_screen_into( + canvas, + VIEWPORT_PADDING, + VIEWPORT_PADDING, + &terminal.screen, + theme, + &RenderOptions { + focused: true, + ..RenderOptions::default() + }, + ); +} + +/// Прочитать ровно `buf.len()` байт по смещению (pread; файл не сдвигается). +fn read_exact_at(file: &File, buf: &mut [u8], offset: u64) -> Result<(), VtFbError> { + let mut done = 0; + while done < buf.len() { + match file.read_at(&mut buf[done..], offset + done as u64) { + Ok(0) => { + return Err(VtFbError::ShortRead { + need: buf.len(), + have: done, + }) + } + Ok(n) => done += n, + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + Err(error) => return Err(VtFbError::from(error)), + } + } + Ok(()) +} + +fn read_u32(bytes: &[u8], offset: usize) -> u32 { + u32::from_le_bytes(bytes[offset..offset + 4].try_into().unwrap()) +} + +fn read_u64(bytes: &[u8], offset: usize) -> u64 { + u64::from_le_bytes(bytes[offset..offset + 8].try_into().unwrap()) +} + +/// Заголовок + пиксели одной поверхности — общий конструктор для mock'ов и +/// тестовых `read()`-файлов. +pub fn encode_snapshot(info: VtFbInfo, pixels: &[u8]) -> Vec { + let mut bytes = Vec::with_capacity(INFO_LEN + pixels.len()); + bytes.extend_from_slice(&info.encode()); + bytes.extend_from_slice(pixels); + bytes +} + +/// Заполнить кадр `stride*height` одним цветом XRGB (тестовый хелпер). +pub fn solid_pixels(info: &VtFbInfo, rgb: (u8, u8, u8)) -> Vec { + let mut pixels = vec![0u8; info.pixels_len()]; + for pixel in pixels.chunks_exact_mut(4) { + pixel[0] = rgb.2; + pixel[1] = rgb.1; + pixel[2] = rgb.0; + pixel[3] = 0; + } + pixels +} + +/// `Read`-обёртка для тестов: прочитать весь тестовый файл как снимок. +pub fn read_snapshot(path: impl AsRef) -> Result, VtFbError> { + let mut file = File::open(path)?; + let mut bytes = Vec::new(); + file.read_to_end(&mut bytes)?; + Ok(bytes) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn info(width: u32, height: u32, generation: u64) -> VtFbInfo { + VtFbInfo { + width, + height, + stride: width * 4, + bpp: 32, + generation, + } + } + + #[test] + fn header_round_trips_through_24_bytes() { + let info = VtFbInfo { + width: 640, + height: 480, + stride: 2560, + bpp: 32, + generation: 0x1122_3344_5566_7788, + }; + let parsed = VtFbInfo::parse(&info.encode()).unwrap(); + assert_eq!(parsed, info); + assert_eq!(info.encode().len(), INFO_LEN); + assert_eq!(parsed.pixels_len(), 2560 * 480); + } + + #[test] + fn header_validation_names_the_violation() { + fn check(mutate: impl Fn(&mut VtFbInfo)) -> String { + let mut info = info(8, 8, 1); + mutate(&mut info); + match VtFbInfo::parse(&info.encode()) { + Err(error) => error.message(), + Ok(_) => panic!("geometry must be rejected"), + } + } + assert!(check(|i| i.bpp = 16).contains("bpp must be 32")); + assert!(check(|i| i.width = 0).contains("non-zero")); + assert!(check(|i| i.stride = 8).contains("stride is smaller")); + assert!(check(|i| i.height = 40_000).contains("exceeds 8192x8192")); + assert!(check(|i| i.width = 9000).contains("exceeds 8192x8192")); + } + + #[test] + fn short_header_is_a_short_read() { + let bytes = info(4, 4, 0).encode(); + match VtFbInfo::parse(&bytes[..INFO_LEN - 1]) { + Err(VtFbError::ShortRead { need, have }) => { + assert_eq!(need, INFO_LEN); + assert_eq!(have, INFO_LEN - 1); + } + other => panic!("expected ShortRead, got {other:?}"), + } + } + + #[test] + fn fit_placement_never_crops_and_never_upscales() { + // 1:1 (окно больше поверхности) — по центру, без растяжения. + let place = fit_placement(640, 400, 900, 600).unwrap(); + assert_eq!( + place, + FitPlacement { + x: 130, + y: 100, + width: 640, + height: 400 + } + ); + // Точно в размер — без смещений. + let place = fit_placement(640, 400, 640, 400).unwrap(); + assert_eq!( + place, + FitPlacement { + x: 0, + y: 0, + width: 640, + height: 400 + } + ); + // Окно меньше: пропорциональный downscale, обе оси в пределах окна. + let place = fit_placement(1024, 768, 900, 600).unwrap(); + assert!(place.width <= 900 && place.height <= 600); + assert_eq!(place.width, 800); + assert_eq!(place.height, 600); + assert_eq!(place.x, 50); + // Очень широкое окно: упираемся в высоту. + let place = fit_placement(1000, 100, 400, 400).unwrap(); + assert_eq!(place.height, 40); + assert_eq!(place.width, 400); + // Ноль с любой стороны — рисовать нечего, но не паника. + assert!(fit_placement(0, 10, 10, 10).is_none()); + assert!(fit_placement(10, 10, 0, 10).is_none()); + } + + #[test] + fn blit_copies_xrgb_into_rgba() { + let info = info(2, 1, 0); + // Пиксель 0: XRGB 0x00112233 (память B,G,R,X); пиксель 1: красный. + let src = vec![0x33, 0x22, 0x11, 0x00, 0x00, 0x00, 0xFF, 0x00]; + let mut canvas = Canvas::new(4, 3, crate::cell::Rgb(1, 2, 3)); + let place = fit_placement(2, 1, 4, 3).unwrap(); + blit_xrgb(&src, &info, &mut canvas, &place).unwrap(); + assert_eq!(canvas.pixel(1, 1), [0x11, 0x22, 0x33, 255]); + assert_eq!(canvas.pixel(2, 1), [0xFF, 0x00, 0x00, 255]); + // Поля вокруг кадра остались фоном темы. + assert_eq!(canvas.pixel(0, 0), [1, 2, 3, 255]); + } + + #[test] + fn blit_rejects_a_truncated_source() { + let info = info(2, 2, 0); + let src = vec![0u8; 8]; + let mut canvas = Canvas::new(2, 2, crate::cell::Rgb(0, 0, 0)); + let place = fit_placement(2, 2, 2, 2).unwrap(); + match blit_xrgb(&src, &info, &mut canvas, &place) { + Err(VtFbError::ShortRead { .. }) => {} + other => panic!("expected ShortRead, got {other:?}"), + } + } + + #[test] + fn errno_helpers_match_the_contract() { + assert!(is_session_end(&io::Error::from_raw_os_error(ENODEV))); + assert!(!is_session_end(&io::Error::from_raw_os_error(2))); + assert!(is_missing_device(&io::Error::from_raw_os_error(2))); + assert!(!is_missing_device(&io::Error::from_raw_os_error(ENODEV))); + assert!(VtFbError::from(io::Error::from_raw_os_error(ENODEV)).is_ended()); + assert!(!VtFbError::from(io::Error::from_raw_os_error(13)).is_ended()); + } + + #[test] + fn solid_pixels_and_snapshot_helpers_agree() { + let info = info(2, 2, 7); + let pixels = solid_pixels(&info, (0x11, 0x22, 0x33)); + assert_eq!(pixels.len(), 16); + let snapshot = encode_snapshot(info, &pixels); + assert_eq!(&snapshot[..INFO_LEN], &info.encode()); + assert_eq!(VtFbInfo::parse(&snapshot[..INFO_LEN]).unwrap(), info); + } +} diff --git a/rust-apps/pagh-terminal/src/lib.rs b/rust-apps/pagh-terminal/src/lib.rs index e27dcf23..8fb085fb 100644 --- a/rust-apps/pagh-terminal/src/lib.rs +++ b/rust-apps/pagh-terminal/src/lib.rs @@ -13,9 +13,12 @@ //! surface, Linux-keyboard-to-VT input encoding. //! * [`vtconsole`] — parser for the proposed kernel VT console shared text //! surface (ABI v1, see `TERMINAL.md`). +//! * [`kernelsession`] — kernel shell-session surface (`/dev/vtfb1` pixels + +//! `/dev/vtinput1` keys): the default windowed mode. Safe half only; the +//! mmap/ioctl glue lives in the binary, so this runs on host mocks. //! * [`demo`] — built-in demo shell and deterministic screenshot generator. //! * [`session`] / [`sh`] — a real shell child behind two pipes for the terminal -//! window, and the minimal userspace shell it runs (boot-VT mirror is opt-in). +//! window, and the minimal userspace shell it runs (fallback/test mode). #![forbid(unsafe_code)] @@ -24,6 +27,7 @@ pub mod client; pub mod demo; pub mod font; pub mod font_index; +pub mod kernelsession; pub mod keys; pub mod parser; pub mod png; diff --git a/rust-apps/pagh-terminal/src/render.rs b/rust-apps/pagh-terminal/src/render.rs index e9bc75a7..38b387c3 100644 --- a/rust-apps/pagh-terminal/src/render.rs +++ b/rust-apps/pagh-terminal/src/render.rs @@ -193,6 +193,30 @@ impl Canvas { self.pixels[i + 3] = 255; } + /// Записать пиксель RGBA без блендинга. + /// + /// Вход для блита внешней поверхности (kernel-session): цвет приходит + /// байтами из чужого framebuffer'а, а не из темы, поэтому `put(Rgb)` не + /// подходит — нужен точный контроль над всеми четырьмя байтами. Для + /// mapped-поверхности (`ShmSurface`) порядок тот же, что у `put`: провод + /// ждёт XRGB8888 little-endian (`B,G,R,0`). + pub fn set_pixel_rgba(&mut self, x: usize, y: usize, rgba: [u8; 4]) { + if x >= self.width || y >= self.height { + return; + } + if let Some(mapping) = &mut self.mapping { + let i = y * self.stride + x * 4; + let bytes = mapping.as_mut_slice(); + bytes[i] = rgba[2]; + bytes[i + 1] = rgba[1]; + bytes[i + 2] = rgba[0]; + bytes[i + 3] = 0; + return; + } + let i = (y * self.width + x) * 4; + self.pixels[i..i + 4].copy_from_slice(&rgba); + } + /// Alpha-blend `color` over the existing pixel. pub fn blend_pixel(&mut self, x: usize, y: usize, color: Rgb, alpha: u8) { if x >= self.width || y >= self.height || alpha == 0 { diff --git a/rust-apps/pagh-terminal/tests/headless_cli.rs b/rust-apps/pagh-terminal/tests/headless_cli.rs index 00f70466..290f3ce9 100644 --- a/rust-apps/pagh-terminal/tests/headless_cli.rs +++ b/rust-apps/pagh-terminal/tests/headless_cli.rs @@ -274,7 +274,7 @@ fn live_binary_talks_pdp1_and_exits_on_server_close() { let mut child = Command::new(binary()) .args(["--socket"]) .arg(&socket) - .args(["--size", "320x200", "--title", "Test"]) + .args(["--size", "320x200", "--title", "Test", "--demo-shell"]) .stdout(Stdio::null()) .stderr(Stdio::null()) .spawn() diff --git a/rust-apps/pagh-terminal/tests/kernel_session.rs b/rust-apps/pagh-terminal/tests/kernel_session.rs new file mode 100644 index 00000000..9ecc3a1b --- /dev/null +++ b/rust-apps/pagh-terminal/tests/kernel_session.rs @@ -0,0 +1,583 @@ +//! Контракт окна kernel-session (`/dev/vtfb1` + `/dev/vtinput1`) без ядра. +//! +//! Здесь проверяется ровно то, что обещает режим: `generation`-гейт, блит +//! (1:1 / downscale / letterbox), честные ошибки устройств и завершения +//! сессии, VT-кодирование клавиш и `read()`-fallback. Mock-устройство +//! подменяет поверхность ядра через публичные трейты +//! [`pagh_terminal::kernelsession::FrameSource`] и +//! [`pagh_terminal::kernelsession::InputSink`] — на хосте `/dev/vtfb1` нет, +//! поэтому без абстракции этот режим нельзя было бы проверить вообще. +//! +//! Отдельно проверяется поведение самого бинаря: `--help` называет режим, а +//! отсутствие устройств даёт честную строку в stderr и откат на pipe-сессию. + +use std::io::{self, Write}; +use std::os::unix::net::UnixListener; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::time::Duration; + +use pagh_terminal::kernelsession::{ + encode_key_bytes, encode_snapshot, fit_placement, is_missing_device, is_session_end, + render_notice, solid_pixels, Draw, FileInput, FitPlacement, FrameSource, InputSink, + KernelFrame, KeyForwarder, ReadFrameSource, VtFbError, VtFbInfo, +}; +use pagh_terminal::protocol::{self, configure_flags, welcome_flags, Message}; +use pagh_terminal::render::{Canvas, Theme}; + +fn binary() -> &'static str { + env!("CARGO_BIN_EXE_pagh-terminal") +} + +fn temp_dir(tag: &str) -> PathBuf { + let mut dir = std::env::temp_dir(); + dir.push(format!( + "pagh-term-kernelsession-{tag}-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +fn info(width: u32, height: u32, generation: u64) -> VtFbInfo { + VtFbInfo { + width, + height, + stride: width * 4, + bpp: 32, + generation, + } +} + +/// Mock-поверхность сессии ядра: пиксели + generation в памяти хоста. +struct MockFb { + info: VtFbInfo, + pixels: Vec, + polls: usize, + /// Что вернуть из `poll()` вместо кадра: `ended`, `io` или `short`. + failure: Option<&'static str>, + /// Сколько `poll()`-ов отдать кадр до отказа (0 — отказ сразу). + fail_after: usize, +} + +impl MockFb { + fn new(info: VtFbInfo, rgb: (u8, u8, u8)) -> MockFb { + MockFb { + pixels: solid_pixels(&info, rgb), + info, + polls: 0, + failure: None, + fail_after: 0, + } + } + + /// Опубликовать новый кадр: generation растёт, пиксели меняются. + fn publish(&mut self, rgb: (u8, u8, u8)) { + self.info.generation += 1; + self.pixels = solid_pixels(&self.info, rgb); + } +} + +impl FrameSource for MockFb { + fn poll(&mut self) -> Result { + self.polls += 1; + if self.polls <= self.fail_after { + return Ok(self.info); + } + match self.failure { + Some("ended") => Err(VtFbError::Ended), + Some("io") => Err(VtFbError::Io(io::Error::other("device exploded"))), + _ => Ok(self.info), + } + } + + fn with_pixels(&mut self, f: &mut dyn FnMut(&[u8])) -> Result<(), VtFbError> { + if self.failure == Some("short") { + let short = self.pixels.len() / 2; + f(&self.pixels[..short]); + return Ok(()); + } + f(&self.pixels); + Ok(()) + } +} + +/// Куда «устройство ввода» складывает байты в тестах. +struct MockInput { + written: Vec, +} + +impl InputSink for MockInput { + fn send(&mut self, bytes: &[u8]) -> io::Result<()> { + self.written.extend_from_slice(bytes); + Ok(()) + } +} + +#[test] +fn first_frame_is_blitted_and_an_idle_poll_draws_nothing() { + let fb = MockFb::new(info(4, 2, 1), (0x10, 0x20, 0x30)); + let mut frame = KernelFrame::open(fb).expect("open"); + let theme = Theme::default(); + let mut canvas = Canvas::new(8, 6, theme.bg); + + assert_eq!( + frame.draw_if_changed(&mut canvas, &theme).unwrap(), + Draw::Drawn { generation: 1 } + ); + // 1:1 по центру: поверхность 4×2 внутри окна 8×6 → x=2, y=2. + assert_eq!(canvas.pixel(2, 2), [0x10, 0x20, 0x30, 255]); + assert_eq!(canvas.pixel(5, 3), [0x10, 0x20, 0x30, 255]); + // Поля — фон темы, а не чужой пиксель. + assert_eq!( + canvas.pixel(0, 0), + [theme.bg.0, theme.bg.1, theme.bg.2, 255] + ); + + let polls_before = frame.info().generation; + assert_eq!( + frame.draw_if_changed(&mut canvas, &theme).unwrap(), + Draw::Unchanged, + "generation не менялась — кадр перерисовываться не должен" + ); + assert_eq!(frame.info().generation, polls_before); +} + +#[test] +fn invalidate_forces_a_full_repaint_for_the_new_canvas() { + let fb = MockFb::new(info(3, 3, 5), (1, 2, 3)); + let mut frame = KernelFrame::open(fb).expect("open"); + let theme = Theme::default(); + let mut canvas = Canvas::new(3, 3, theme.bg); + assert_eq!( + frame.draw_if_changed(&mut canvas, &theme).unwrap(), + Draw::Drawn { generation: 5 } + ); + assert_eq!( + frame.draw_if_changed(&mut canvas, &theme).unwrap(), + Draw::Unchanged + ); + // Ресайз окна/новый memfd: generation та же, но холст пуст — нужен полный + // блит, иначе окно осталось бы фоном темы. + frame.invalidate(); + let mut fresh = Canvas::new(3, 3, theme.bg); + assert_eq!( + frame.draw_if_changed(&mut fresh, &theme).unwrap(), + Draw::Drawn { generation: 5 } + ); + assert_eq!(fresh.pixel(0, 0), [1, 2, 3, 255]); +} + +#[test] +fn a_republished_frame_reaches_the_window() { + let theme = Theme::default(); + let mut canvas = Canvas::new(2, 2, theme.bg); + { + let mut frame = KernelFrame::open(MockFb::new(info(2, 2, 10), (0, 0, 0))).expect("open"); + frame.draw_if_changed(&mut canvas, &theme).unwrap(); + assert_eq!(canvas.pixel(0, 0), [0, 0, 0, 255]); + } + + // Второй кадр: ядро перекрасило сессию и подняло generation. + let mut fb = MockFb::new(info(2, 2, 10), (0, 0, 0)); + fb.publish((0xAA, 0xBB, 0xCC)); + assert_eq!(fb.info.generation, 11); + let mut frame = KernelFrame::open(fb).expect("reopen"); + let mut canvas = Canvas::new(2, 2, theme.bg); + assert_eq!( + frame.draw_if_changed(&mut canvas, &theme).unwrap(), + Draw::Drawn { generation: 11 } + ); + assert_eq!(canvas.pixel(1, 1), [0xAA, 0xBB, 0xCC, 255]); +} + +#[test] +fn a_small_window_shows_the_whole_frame_scaled_down() { + let fb = MockFb::new(info(16, 8, 1), (0x33, 0x44, 0x55)); + let mut frame = KernelFrame::open(fb).expect("open"); + let theme = Theme::default(); + let mut canvas = Canvas::new(8, 4, theme.bg); + assert_eq!( + frame.draw_if_changed(&mut canvas, &theme).unwrap(), + Draw::Drawn { generation: 1 } + ); + // Пропорции сохранены (16:8 → 8:4), отступов нет: кадр занимает окно. + let place = fit_placement(16, 8, 8, 4).unwrap(); + assert_eq!( + place, + FitPlacement { + x: 0, + y: 0, + width: 8, + height: 4 + } + ); + for (x, y) in [(0, 0), (7, 0), (0, 3), (7, 3)] { + assert_eq!( + canvas.pixel(x, y), + [0x33, 0x44, 0x55, 255], + "downscale обязан покрыть всё окно" + ); + } +} + +#[test] +fn session_end_is_reported_honestly_and_not_masked() { + let mut fb = MockFb::new(info(2, 2, 1), (0, 0, 0)); + fb.failure = Some("ended"); + // Первый poll (open) отдаёт кадр: сессия завершается уже внутри цикла. + fb.fail_after = 1; + let mut frame = KernelFrame::open(fb).expect("open passes before the failure"); + let theme = Theme::default(); + let mut canvas = Canvas::new(4, 4, theme.bg); + match frame.draw_if_changed(&mut canvas, &theme) { + Err(error) if error.is_ended() => { + assert!( + error.message().contains("relaunch"), + "сообщение обязано говорить, как переподключиться: {}", + error.message() + ); + } + other => panic!("expected Ended, got {other:?}"), + } +} + +#[test] +fn device_errors_are_device_errors() { + let mut fb = MockFb::new(info(2, 2, 1), (0, 0, 0)); + fb.failure = Some("io"); + fb.fail_after = 1; + let mut frame = KernelFrame::open(fb).expect("open"); + let theme = Theme::default(); + let mut canvas = Canvas::new(4, 4, theme.bg); + match frame.draw_if_changed(&mut canvas, &theme) { + Err(VtFbError::Io(error)) => assert!(error.to_string().contains("device exploded")), + other => panic!("expected Io, got {other:?}"), + } +} + +#[test] +fn a_short_frame_is_an_error_not_a_partial_picture() { + let mut fb = MockFb::new(info(4, 4, 1), (0, 0, 0)); + fb.failure = Some("short"); + fb.fail_after = 1; + let mut frame = KernelFrame::open(fb).expect("open"); + let theme = Theme::default(); + let mut canvas = Canvas::new(4, 4, theme.bg); + match frame.draw_if_changed(&mut canvas, &theme) { + Err(VtFbError::ShortRead { need, have }) => { + assert_eq!(need, 4 * 4 * 4); + assert_eq!(have, need / 2); + } + other => panic!("expected ShortRead, got {other:?}"), + } +} + +#[test] +fn read_fallback_tracks_generation_on_a_plain_file() { + let dir = temp_dir("readfb"); + let path = dir.join("vtfb1"); + let first = info(3, 2, 1); + std::fs::write( + &path, + encode_snapshot(first, &solid_pixels(&first, (0x01, 0x02, 0x03))), + ) + .unwrap(); + + let source = ReadFrameSource::open(&path).expect("open snapshot"); + let mut frame = KernelFrame::open(source).expect("kernel frame"); + let theme = Theme::default(); + let mut canvas = Canvas::new(3, 2, theme.bg); + assert_eq!( + frame.draw_if_changed(&mut canvas, &theme).unwrap(), + Draw::Drawn { generation: 1 } + ); + assert_eq!(canvas.pixel(2, 1), [0x01, 0x02, 0x03, 255]); + + // Ядро переписало поверхность: заголовок и пиксели одним снимком. + let second = info(3, 2, 2); + std::fs::write( + &path, + encode_snapshot(second, &solid_pixels(&second, (0xF0, 0xE0, 0xD0))), + ) + .unwrap(); + assert_eq!( + frame.draw_if_changed(&mut canvas, &theme).unwrap(), + Draw::Drawn { generation: 2 } + ); + assert_eq!(canvas.pixel(0, 0), [0xF0, 0xE0, 0xD0, 255]); + assert_eq!( + frame.draw_if_changed(&mut canvas, &theme).unwrap(), + Draw::Unchanged + ); + + // Обрезанный снимок — честная ошибка, а не наполовину нарисованный кадр. + // Generation выше прежней, иначе клиент даже не станет читать пиксели. + let truncated = info(3, 2, 3); + std::fs::write( + &path, + &encode_snapshot(truncated, &solid_pixels(&truncated, (0, 0, 0)))[..30], + ) + .unwrap(); + match frame.draw_if_changed(&mut canvas, &theme) { + Err(VtFbError::ShortRead { .. }) => {} + other => panic!("expected ShortRead, got {other:?}"), + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn keys_become_vt_bytes_for_the_kernel_input() { + let mut forwarder = KeyForwarder::new(MockInput { + written: Vec::new(), + }); + use pagh_terminal::keys::evdev; + // PDP/1 modifier bits (same wire values as `protocol::mods`). + const MOD_CTRL: u32 = 1 << 1; + + // Нажатие printable-клавиши. + assert_eq!( + forwarder + .handle_key(evdev::KEY_H, true, 0) + .expect("write h"), + 1 + ); + // Release ничего не пишет: события отпускания kernel-shell'у не нужны. + assert_eq!( + forwarder + .handle_key(evdev::KEY_H, false, 0) + .expect("release"), + 0 + ); + // Enter — CR, как в существующем режиме `/dev/vtinput`. + assert_eq!( + forwarder + .handle_key(evdev::KEY_ENTER, true, 0) + .expect("enter"), + 1 + ); + // Ctrl+C — байт 0x03 (сигнал доставляет само ядро, клиент не имитирует). + assert_eq!( + forwarder + .handle_key(evdev::KEY_C, true, MOD_CTRL) + .expect("ctrl-c"), + 1 + ); + assert_eq!(forwarder.sink().written, b"h\r\x03"); + // И та же кодировка доступна без трейта — ею пользуется окно. + assert_eq!(encode_key_bytes(evdev::KEY_H, true, 0), b"h"); +} + +#[test] +fn file_input_writes_the_bytes_it_is_given() { + let dir = temp_dir("input"); + let path = dir.join("vtinput1"); + std::fs::write(&path, b"").unwrap(); + let mut sink = FileInput::open(&path).expect("open input file"); + sink.send(b"echo hi\r").expect("send"); + sink.send(b"x").expect("send again"); + assert_eq!(std::fs::read(&path).unwrap(), b"echo hi\rx"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_notice_is_rendered_into_the_window() { + let theme = Theme::default(); + let mut canvas = Canvas::new(320, 120, theme.bg); + let blank = canvas.pixel(100, 60); + render_notice( + &mut canvas, + &theme, + &[ + "[kernel session] the shell session has ended.", + "", + "Relaunch to reconnect.", + ], + ); + let changed = (0..canvas.width) + .flat_map(|x| (0..canvas.height).map(move |y| (x, y))) + .filter(|&(x, y)| canvas.pixel(x, y) != blank) + .count(); + assert!( + changed > 50, + "сообщение обязано быть видимым (изменено {changed} px)" + ); +} + +#[test] +fn errno_classification_matches_the_device_contract() { + assert!(is_session_end(&io::Error::from_raw_os_error(19))); + assert!(is_missing_device(&io::Error::from_raw_os_error(2))); + assert!(!is_missing_device(&io::Error::from_raw_os_error(13))); +} + +#[test] +fn help_names_the_kernel_session_mode_and_its_devices() { + let help = Command::new(binary()).arg("--help").output().unwrap(); + assert!(help.status.success()); + let text = String::from_utf8_lossy(&help.stdout); + for needle in [ + "KERNEL SHELL SESSION", + "/dev/vtfb1", + "/dev/vtinput1", + "--vt-fb", + "--pipe-shell", + "--demo-shell", + "no PTY/termios", + ] { + assert!(text.contains(needle), "help must mention {needle:?}"); + } +} + +/// FPDP/1-заглушка: hello → welcome (без ShmSurface) → create → configure/focus +/// → один commit. Дальше тест сам решает, послать close. +fn spawn_fake_desktop( + socket: &Path, +) -> (std::thread::JoinHandle<()>, std::sync::mpsc::Receiver<()>) { + let listener = UnixListener::bind(socket).unwrap(); + let (tx, rx) = std::sync::mpsc::channel(); + let handle = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(10))) + .unwrap(); + match protocol::read_message(&mut stream).unwrap() { + Message::Hello { app, .. } => assert_eq!(app, "pagh-terminal"), + other => panic!("expected hello, got {other:?}"), + } + stream + .write_all( + &Message::Welcome { + version: 1, + client_id: 7, + width: 1280, + height: 720, + flags: welcome_flags::FORMAT_XRGB8888 | welcome_flags::FORMAT_RGB565, + } + .encode(), + ) + .unwrap(); + match protocol::read_message(&mut stream).unwrap() { + Message::Create { window_id, .. } => assert_eq!(window_id, 101), + other => panic!("expected create, got {other:?}"), + } + for message in [ + Message::Focus { + window_id: 101, + focused: true, + }, + Message::Configure { + window_id: 101, + x: 0, + y: 0, + width: 320, + height: 200, + flags: configure_flags::FOCUSED | configure_flags::RESIZABLE, + }, + ] { + stream.write_all(&message.encode()).unwrap(); + } + // Первый кадр: у fallback-сессии это prompt userspace-shell'а. + match protocol::read_message(&mut stream).unwrap() { + Message::Commit { .. } | Message::ShmOffer { .. } => {} + other => panic!("expected a frame, got {other:?}"), + } + let _ = tx.send(()); + // Композитор закрывает окно (как кнопкой): клиент обязан завершиться + // сам, иначе `Command::output()` в тесте повис бы навсегда. + stream + .write_all( + &Message::Close { + window_id: 101, + reason: protocol::close_reason::SERVER, + } + .encode(), + ) + .unwrap(); + std::thread::sleep(Duration::from_millis(100)); + }); + (handle, rx) +} + +#[test] +fn missing_kernel_devices_fall_back_to_the_pipe_shell_session() { + let dir = temp_dir("fallback"); + let socket = dir.join("desktop.sock"); + let (server, ready) = spawn_fake_desktop(&socket); + let missing_fb = dir.join("no-such-vtfb1"); + let missing_input = dir.join("no-such-vtinput1"); + + let out = Command::new(binary()) + .args(["--socket"]) + .arg(&socket) + .args(["--size", "320x200"]) + .arg("--vt-fb") + .arg(&missing_fb) + .arg("--vt-input") + .arg(&missing_input) + .stdout(Stdio::null()) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("falling back to the private userspace shell session"), + "отсутствие устройства обязано быть названо честно: {stderr}" + ); + assert!( + !stderr.contains("kernel session unavailable"), + "отсутствие устройства — не ошибка устройства: {stderr}" + ); + assert!(ready.recv_timeout(Duration::from_secs(10)).is_ok()); + server.join().expect("fake compositor"); + assert!( + out.status.success(), + "fallback-клиент обязан штатно закрыться по close: {:?}", + out.status + ); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_regular_file_surface_uses_read_fallback_and_reports_a_missing_compositor() { + let dir = temp_dir("readfallback"); + let surface = dir.join("vtfb1"); + let first = info(8, 6, 1); + std::fs::write( + &surface, + encode_snapshot(first, &solid_pixels(&first, (0x20, 0x30, 0x40))), + ) + .unwrap(); + let input = dir.join("vtinput1"); + std::fs::write(&input, b"").unwrap(); + + let out = Command::new(binary()) + .args(["--socket"]) + .arg(dir.join("no-desktop.sock")) + .args(["--size", "320x200"]) + .arg("--vt-fb") + .arg(&surface) + .arg("--vt-input") + .arg(&input) + .stdout(Stdio::null()) + .output() + .unwrap(); + assert_eq!(out.status.code(), Some(2), "ошибка обязана быть видимой"); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("read() snapshots"), + "ioctl недоступен — обязан быть назван read()-fallback: {stderr}" + ); + assert!( + stderr.contains("kernel session 8x6"), + "геометрия поверхности обязана быть в логе: {stderr}" + ); + assert!( + stderr.contains("no-desktop.sock"), + "причина отказа композитора обязана быть названа: {stderr}" + ); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/rust-apps/pagh-terminal/tests/pdp_e2e.rs b/rust-apps/pagh-terminal/tests/pdp_e2e.rs index decabc12..0982e911 100644 --- a/rust-apps/pagh-terminal/tests/pdp_e2e.rs +++ b/rust-apps/pagh-terminal/tests/pdp_e2e.rs @@ -103,7 +103,14 @@ fn pagh_terminal_runs_under_real_pagh_desktop() { let empty = capture(&server.control, &shots, "00-empty.png"); let trace = shots.join("terminal.trace"); let mut child = Command::new(env!("CARGO_BIN_EXE_pagh-terminal")) - .args(["--socket", socket.to_str().unwrap(), "--size", "700x460"]) + .args([ + "--socket", + socket.to_str().unwrap(), + "--size", + "700x460", + // Explicit mode: this test drives the demo-shell surface end to end. + "--demo-shell", + ]) .env("PAGH_TERMINAL_PDP_TRACE", &trace) .stdout(Stdio::null()) .stderr(Stdio::null()) diff --git a/rust-apps/pagh-terminal/tests/shm_e2e.rs b/rust-apps/pagh-terminal/tests/shm_e2e.rs index cf5f285d..56353065 100644 --- a/rust-apps/pagh-terminal/tests/shm_e2e.rs +++ b/rust-apps/pagh-terminal/tests/shm_e2e.rs @@ -323,6 +323,9 @@ fn terminal_shm_damage_blink_and_resize() { path.to_str().unwrap(), "--size", &format!("{W}x{H}"), + // Explicit mode: ShmSurface framing, independent of the kernel + // shell-session devices host CI does not have. + "--demo-shell", ]) .stdout(Stdio::null()) .stderr(Stdio::null()) From 8fd9fa1d001367d46d044274b0bcf9374cf7a1aa Mon Sep 17 00:00:00 2001 From: pagh-agent Date: Thu, 19 Nov 2026 13:57:36 +0300 Subject: [PATCH 02/12] docs(terminal): document the kernel-session mode and its honest edges MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TERMINAL.md promised a text shared surface and a private pipe shell; both are now secondary to the kernel shell-session window. Without this update the docs still say `--socket` starts a userspace shell, which is exactly the behaviour this branch removed from the default. New section "Режим kernel-session (по умолчанию)" records the device contract (ioctl 0x4700 / 24-byte header / mmap / read() fallback / ENODEV), the frame loop (generation gate, full blit, damage 16 ms throttle, 6 ms idle), the blit policy and why it never crops or upscales, key encoding and why arrow keys stay in normal mode, the exit/error matrix (ENODEV notice, missing device -> pipe fallback, broken device -> in-window error, exit code 2), the trait split that makes the mode host-testable, and the gaps that are still open: no PTY/termios/TIOCGWINSZ/SIGWINCH, no terminal job control, no DEC modes on a pixel surface, one session per window, scrollback/selection left in the kernel, and no live QEMU run yet. The pipe-shell section is relabelled as the fallback/test mode it now is, the mode list and module table include kernelsession.rs and devfs.rs, and the checks section carries the real numbers (159 host tests) plus the fact that pdp/shm e2e now pass --demo-shell explicitly instead of relying on the old default. --- rust-apps/pagh-terminal/README.md | 55 +++++-- rust-apps/pagh-terminal/TERMINAL.md | 228 ++++++++++++++++++++++++---- 2 files changed, 242 insertions(+), 41 deletions(-) diff --git a/rust-apps/pagh-terminal/README.md b/rust-apps/pagh-terminal/README.md index b878f26b..9521b8e7 100644 --- a/rust-apps/pagh-terminal/README.md +++ b/rust-apps/pagh-terminal/README.md @@ -27,7 +27,14 @@ E2E с реальным композитором: `pagh-desktop` из dev (PR #1 без bit 2 обслуживается прежним полным кадром. * ABI v1 kernel console shared surface: валидатор, reader, конвертация в экран (`/dev/vtconsole0`, `/dev/vtinput`), см. [TERMINAL.md](TERMINAL.md). -* 120 host-тестов, включая эталонные escape-последовательности и скриншоты. +* **Режим kernel-session (по умолчанию для `--socket`)**: окно блитит пиксели + поверхности сессии ядра `/dev/vtfb1` (ioctl `0x4700` + `mmap`) и передаёт + клавиатуру в `/dev/vtinput1`. Команды, эхо, редактирование строки и + scrollback делает ядро; клиент рендерит и передаёт ввод, ничего не имитируя. + Масштаб/центрирование — по `generation`, ошибки устройств и `exit` в сессии + показываются в окне честно. Детали и границы — в [TERMINAL.md](TERMINAL.md). +* 159 host-тестов, включая эталонные escape-последовательности, скриншоты и + mock-устройства kernel-session (на хосте `/dev/vtfb1` нет). ## Сборка и проверки @@ -57,16 +64,21 @@ cargo run -- --headless --demo 01-welcome --out /tmp/welcome.png --print cargo run -- --headless --script session.bin --cols 100 --rows 30 \ --out /tmp/session.png --print -# живое окно через compositor (task desktop-server) +# живое окно через compositor: сессия ядра (/dev/vtfb1 + /dev/vtinput1) — +# это режим по умолчанию, никаких специальных флагов не нужно cargo run -- --socket /tmp/pagh-desktop.sock --size 900x600 -# окно с собственной shell-сессией (по умолчанию для --vt + --socket): -# дочерний shell за pipe'ами, boot-VT не читается и ввод в lxrun не уходит -cargo run -- --vt /dev/vtconsole0 --socket /tmp/pagh-desktop.sock +# другой worktree/ядро: подменить устройства поверхности и ввода +cargo run -- --socket /tmp/pagh-desktop.sock \ + --vt-fb /dev/vtfb1 --vt-input /dev/vtinput1 -# диагностика: по-прежнему зеркалить boot-VT в окне -cargo run -- --vt /dev/vtconsole0 --vt-input /dev/vtinput \ - --socket /tmp/pagh-desktop.sock --mirror-vt +# демо-шелл (скриншоты, A/B) и userspace-shell за pipe'ами (fallback/тест) — +# оба режима сохранены, но больше не по умолчанию +cargo run -- --socket /tmp/pagh-desktop.sock --demo-shell +cargo run -- --socket /tmp/pagh-desktop.sock --pipe-shell + +# диагностика: зеркалить boot-VT (--vt + --socket) или один снимок (без --socket) +cargo run -- --vt /dev/vtconsole0 --socket /tmp/pagh-desktop.sock --mirror-vt ``` Headless-демо: `01-welcome`, `02-colors`, `03-scrollback`, `04-unicode`. @@ -75,13 +87,26 @@ Headless-демо: `01-welcome`, `02-colors`, `03-scrollback`, `04-unicode`. ## Ограничения -Полноценного PTY нет (ABI v1 kernel console surface описан в -[TERMINAL.md](TERMINAL.md)). Live-режим подключается к `pagh-desktop` по PDP/1: -окно запускает собственный shell-потомок через pipe'ы (минимальный userspace -shell `help/ls/cd/pwd/echo/cat/uname/clear/exit`), а не зеркалит boot-VT; -`--mirror-vt` возвращает старое зеркало для диагностики. ShmSurface включается только если -сервер объявил `welcome.flags` bit 2 (иначе — полный кадр). Нет reflow при -resize, +Live-режим подключается к `pagh-desktop` по PDP/1 и по умолчанию показывает +сессию ядра: клиент блитит `/dev/vtfb1` и пишет клавиши в `/dev/vtinput1`. +Полный набор команд (`df`, `ps`, `ppkg`, `lxrun`, `disk`, `nano`, history, +редактирование строки, scrollback) — это ядро; в клиенте их нет вообще. +Если устройств нет (старое ядро), окно говорит об этом в stderr и +откатывается на прежнюю pipe-сессию с userspace-shell'ом +(`help/ls/cd/pwd/echo/cat/uname/clear/exit`, флаг `--pipe-shell`, он же +`--vt` + `--socket`); `--mirror-vt` возвращает зеркало boot-VT для +диагностики, `--demo-shell` — демо-шелл. + +Честные границы kernel-session: нет PTY/termios, нет `TIOCGWINSZ`/SIGWINCH +(размер знает только ядро), `Ctrl+C`/`Ctrl+Z` — просто байты в +`/dev/vtinput1` (сигналы доставляет ядро), пиксельная поверхность не несёт +DEC-режимов, поэтому стрелки всегда идут в normal-кадрах; одна сессия на +окно, scrollback/selection остаются в ядре и колесом не листаются. При +уменьшении окна кадр масштабируется nearest-neighbour (без обрезки и без +апскейла). Интеграция с kernel-веткой пока не проверена live: устройства +реализуются в параллельной ветке, клиент проверен на mock-устройствах и +`read()`-fallback'е. ShmSurface включается только если сервер объявил +`welcome.flags` bit 2 (иначе — полный кадр). Нет reflow при resize, комбинирующие метки не компонуются, OSC 4/8/52 игнорируются. Подробно — [TERMINAL.md](TERMINAL.md). diff --git a/rust-apps/pagh-terminal/TERMINAL.md b/rust-apps/pagh-terminal/TERMINAL.md index ae9a0d97..c3ed9ee9 100644 --- a/rust-apps/pagh-terminal/TERMINAL.md +++ b/rust-apps/pagh-terminal/TERMINAL.md @@ -10,6 +10,16 @@ headless-тестов и клиент PDP/1 (Pagh Desktop Protocol). Отдел клиента, ABI-парсер shared surface и host-тесты работают; реальный compositor, `/dev/fb0`, evdev и kernel-устройство VT ещё не подключены. +Оконный режим по умолчанию — **kernel-session**: окно блитит пиксельную +поверхность сессии ядра (`/dev/vtfb1`) и передаёт клавиатуру в +`/dev/vtinput1`, то есть показывает настоящую kernel-shell-сессию со всеми её +командами (`df`, `ps`, `ppkg`, `lxrun`, `disk`, `nano`, history, +редактирование строки, scrollback). Клиент в этом режиме рендерит и передаёт +ввод — и ничего не имитирует. Kernel-сторона контракта реализуется +параллельно; live-интеграция в QEMU ещё не прогонялась, поэтому клиент +проверен на mock-устройствах и `read()`-fallback'е (см. +[Режим kernel-session](#режим-kernel-session-по-умолчанию)). + ![Welcome](screenshots/01-welcome.png) ## Содержание @@ -19,9 +29,10 @@ headless-тестов и клиент PDP/1 (Pagh Desktop Protocol). Отдел 3. [Покрытие парсера](#покрытие-парсера) 4. [Рендерер](#рендерер) 5. [Клиентский протокол PDP/1](#клиентский-протокол-pdp1) -6. [Kernel console shared surface ABI v1](#kernel-console-shared-surface-abi-v1) -7. [Ограничения и остаток](#ограничения-и-остаток) -8. [Проверки](#проверки) +6. [Режим kernel-session (по умолчанию)](#режим-kernel-session-по-умолчанию) +7. [Kernel console shared surface ABI v1](#kernel-console-shared-surface-abi-v1) +8. [Ограничения и остаток](#ограничения-и-остаток) +9. [Проверки](#проверки) ## Быстрый старт @@ -54,12 +65,19 @@ bare-metal target, поэтому для host-сборки std пересоби `pagh-terminal --help` перечисляет режимы: +* `--socket PATH` — окно через PDP/1 (hello/create/commit/input/configure), + по умолчанию подключённое к **сессии ядра** (`/dev/vtfb1` + `/dev/vtinput1`); * `--headless --demo NAME|--script FILE` — отрисовать кадр/текст; -* `--socket PATH` — окно через PDP/1 (hello/create/commit/input/configure); * `--vt /dev/vtconsole0` — читать shared surface ядра (ABI v1) и писать ввод - в `/dev/vtinput`; + в `/dev/vtinput`; с `--socket` это legacy-окно: `--mirror-vt` зеркалит + boot-VT, иначе поднимается userspace-shell за pipe'ами; +* `--pipe-shell` / `--demo-shell` — явные тестовые/fallback-режимы окна; * `--screenshots DIR` — перегенерировать эталонные PNG. +Устройства kernel-session переопределяются `--vt-fb` (по умолчанию +`/dev/vtfb1`) и `--vt-input` (по умолчанию `/dev/vtinput1` для этого режима и +`/dev/vtinput` для `--vt`/`--mirror-vt`). + ## Архитектура ```text @@ -102,8 +120,10 @@ bare-metal target, поэтому для host-сборки std пересоби | `src/client.rs` | Unix-socket клиент, hello/welcome, create/commit, events | | `src/keys.rs` | evdev → VT-байты: стрелки, F-клавиши, Ctrl/Alt, SGR-мышь, focus, paste | | `src/vtconsole.rs` | валидатор и reader для ABI v1 `/dev/vtconsole0` | +| `src/kernelsession.rs` | режим kernel-session: заголовок `vtfb1` (`VtFbInfo`), `generation`-гейт, блит, ошибки, клавиши; только safe-код | +| `src/bin/pagh-terminal/devfs.rs` | `ioctl 0x4700` + `mmap`/`read()` для `/dev/vtfb1` (весь `unsafe` крейта) | | `src/demo.rs` | demo shell и детерминированные скриншоты | -| `src/bin/pagh-terminal.rs` | CLI-режимы headless/live/vt/screenshots | +| `src/bin/pagh-terminal.rs` | CLI-режимы kernel-session/headless/live/vt/screenshots | ## Покрытие парсера @@ -326,15 +346,19 @@ Resize — только серверный: клиент не просит ра нет. Ошибки: magic/flags/type/payload/stride/pixel-length отклоняются как `InvalidData`; клиент не паникует на обрезанном потоке. -## Оконная shell-сессия (два pipe, не boot-VT) +## Оконная shell-сессия (два pipe, не boot-VT) — fallback/тестовый режим -Окно терминала в desktop B — **отдельная интерактивная сессия**, а не зеркало -загрузочной консоли. При запуске с `--socket` (и без `--mirror-vt`) клиент -запускает процесс-потомок `pagh-terminal --shell-child` с pipe'ами на -stdin/stdout/stderr; вывод потомка идёт в VT-парсер этого окна, клавиатура окна — -в его stdin. `/dev/vtconsole0` не читается, `/dev/vtinput` не трогается: desktop -(`lxrun`) продолжает владеть boot-VT и его foreground-вводом, но больше не -перехватывает набор в окне. +Это **не** режим по умолчанию: по умолчанию окно подключается к сессии ядра +(см. выше). Pipe-сессия осталась как fallback для ядер без `/dev/vtfb1` и как +явный тестовый режим (`--pipe-shell`, или `--vt` + `--socket` без +`--mirror-vt`). + +Окно в этом режиме — **отдельная интерактивная сессия**, а не зеркало +загрузочной консоли: клиент запускает процесс-потомок `pagh-terminal +--shell-child` с pipe'ами на stdin/stdout/stderr; вывод потомка идёт в +VT-парсер этого окна, клавиатура окна — в его stdin. `/dev/vtconsole0` не +читается, `/dev/vtinput` не трогается: desktop (`lxrun`) продолжает владеть +boot-VT и его foreground-вводом, но не перехватывает набор в окне. Почему так, а не переиспользовать kernel-shell: shell ядра — консольная задача (`fb_println!`/`kprintln!` + PS/2-кольцо), её нельзя перенаправить в pipe без @@ -360,9 +384,10 @@ kernel-shell (`df`, `ps`, `pkg`, `lxrun`, …) в сессии недоступ полный кадр 2 МиБ на каждое эхо-нажатие в QEMU-TCG идёт сотни миллисекунд. Если SHM не сложился, сессия молча откатывается на полный кадр (legacy-путь). -Старое поведение осталось для диагностики: `--mirror-vt` рисует в окне снимок -boot-VT и пишет ввод в `/dev/vtinput`, а `--vt PATH` без `--socket` печатает -один снимок в stdout (headless). +Диагностика осталась как была: `--mirror-vt` рисует в окне снимок boot-VT и +пишет ввод в `/dev/vtinput`, а `--vt PATH` без `--socket` печатает один снимок +в stdout (headless). Демо-шелл для скриншотов и A/B доступен явно через +`--demo-shell`. Ограничения сессии (честно, до PTY-этапа): нет управляющего терминала и `struct termios`, нет `TIOCGWINSZ`/SIGWINCH (размер знает только окно), нет @@ -370,6 +395,140 @@ job-control/Ctrl+Z, нет `SIGINT` реальному потомку (`Ctrl+C` stdin), нет echo-режима ядра (эхо делает сам shell-потомок). Кадры идут полным кадром, как в `--vt`-режиме, а не damage'ом. +## Режим kernel-session (по умолчанию) + +Окно терминала в desktop B — **окно на настоящую kernel-shell-сессию**. Ядро +владеет второй сессией своего shell'а (той же, где живут `df`, `ps`, `ppkg`, +`lxrun`, `id`, `groups`, `su`, `login`, `disk`, `nano`, history, редактирование +строки и scrollback), рисует её в собственную пиксельную поверхность, а клиент +только блитит пиксели в своё окно и возвращает нажатия обратно байтами VT. +Ни одной команды в клиенте нет: если сессии нет, окно говорит об этом прямо, а +не показывает «похожий» shell. + +Режим включается сам при `--socket` и выключается явными +`--vt`/`--mirror-vt`/`--pipe-shell`/`--demo-shell` (см. `--help`). + +### Контракт устройств + +| путь | режим | назначение | +|---|---|---| +| `/dev/vtfb1` | read-only | пиксельная поверхность сессии ядра | +| `/dev/vtinput1` | write-only | VT-байты клавиатуры (тот же формат, что `/dev/vtinput`) | + +```c +/* ioctl 0x4700 (VTFBIOGET_INFO) -> 24 байта little-endian */ +struct pgvt_fb_info { + __u32 width; /* 0 */ + __u32 height; /* 4 */ + __u32 stride; /* 8 байт на строку, >= width * 4 */ + __u32 bpp; /* 12 всегда 32 */ + __u64 generation; /* 16 растёт на каждый flush сессии */ +}; + +/* пиксели: mmap(NULL, stride*height, PROT_READ, MAP_SHARED, fd, 0) */ +/* 32bpp XRGB: в памяти B, G, R, X (формат 1 PDP/1) */ +``` + +`read()`-fallback (ядра без mmap поверхности): те же 24 байта заголовка, затем +пиксели, одним `pread`-проходом от offset 0 — заголовок и пиксели принадлежат +одному снимку. Клиент пробует `mmap`, а при отказе (`ENOTTY`/`ENOSYS`/ +`EINVAL`, обычный файл) честно пишет в stderr `falling back to read() +snapshots` и продолжает на `read()`. + +`generation` — единственный сигнал «кадр изменился»: ioctl дёшев (24 байта), +поэтому опрос идёт на каждом витке цикла, а блит — только когда значение +выросло. `exit` в сессии завершает её: устройства начинают отдавать `ENODEV` +(errno 19), а первый `open` любого из них спавнит новую сессию ядра. + +### Кадр + +1. `poll()` — ioctl `0x4700` (или 24 байта заголовка в `read()`-режиме). + Геометрия валидируется **до** блита: `bpp == 32`, ненулевые размеры, + `stride >= width*4`, `width/height <= 8192`, кадр `<= 32 МиБ`. +2. Если `generation` не менялась и не было `invalidate()` — кадр не трогается + (простой окна не жжёт CPU и не шлёт пустых кадров). +3. Иначе — **полный блит** в холст окна и отправка damage-прямоугольников + (`ShmSurface`, если композитор объявил `welcome.flags` bit 2; иначе полный + кадр). Полный блит — осознанный выбор: контракт v1 не даёт частичных + damage от ядра, а «порванный» flush'ем кадр лечится следующим полным + блитом по выросшему `generation`. +4. `invalidate()` (смена размера окна, новый memfd, `configure`) заставляет + перерисовать кадр даже при той же `generation`. + +Отправка кадра троттлится 16 мс, холостой виток спит 6 мс: ввод читается +между кадрами, а не после них. + +### Политика масштабирования + +`fit_placement` выбирает одно из трёх, и это задокументировано, а не выведено +из эвристик: + +* окно **не меньше** поверхности — блит 1:1 по центру, без ресемплинга + (пиксель в пиксель: текст ядра не мылится); +* окно **меньше** — downscale с сохранением пропорций (nearest neighbour, + целочисленная арифметика), по центру, поля заливаются фоном темы; +* **обрезки нет** никогда: вся поверхность сессии видна целиком. Ячейки + kernel-VT — 8×18 px, окно 900×600 почти всегда меньше типичного kernel-fb, и + спрятать правую часть вывода хуже, чем потерять строку пикселей при + downscale; +* **апскейла нет**: большое окно показывает кадр 1:1 по центру, а не мыло. + +### Клавиатура + +Клавиши окна кодируются `keys::encode_key` с `KeyModes::default()` и пишутся в +`/dev/vtinput1` без `flush` (символьное устройство, `write` уже доставил +байты). Release и чистые модификаторы кодируются в пустой вектор и не пишут +ничего. `Ctrl+C`/`Ctrl+Z` — это просто байты (`0x03`/`0x1a`), сигналы +доставляет ядро; клиент ничего не сигналит и не «изображает» shell. + +Почему `KeyModes::default()`: поверхность пиксельная, DEC-режимы (`?1` +application cursor, bracketed paste, mouse) из неё не наблюдаемы. Kernel-shell +их не включает, поэтому normal-стрелки — корректный и единственно возможный +выбор v1 (ограничение названо ниже, а не спрятано). + +### Завершение сессии и ошибки + +| ситуация | поведение | +|---|---| +| `exit` в сессии → `ENODEV` | в окне: «the shell session has ended / relaunch to reconnect», пауза 1.5 с, окно закрывается | +| `/dev/vtfb1` или `/dev/vtinput1` нет (`ENOENT`, старое ядро) | честная строка в stderr + откат на pipe-сессию (`--pipe-shell`-путь) | +| устройство есть, но ioctl/mmap/read/write не работают | честное сообщение **в окне** + код возврата 2, без отката в демо | +| mmap поверхности недоступен | `read()`-снимки (задокументированный fallback) | +| кадр короче `stride*height` | `ShortRead` — ошибка, а не наполовину нарисованный кадр | + +Реконнект — **повторный запуск окна**, а не кнопка в нём: сессию спавнит ядро +на первом `open`, а «предложить reconnect» в пиксельном зеркале пришлось бы +делать отдельным UI ввода, которого в v1 нет. Пауза перед закрытием нужна, +чтобы сообщение успели прочитать, а не чтобы спрятать конец сессии. + +### Тестируемость + +`lib.rs` объявляет `#![forbid(unsafe_code)]`, поэтому `mmap`/`ioctl` живут +только в `src/bin/pagh-terminal/devfs.rs`, а вся логика режима — в +`src/kernelsession.rs` за трейтами `FrameSource` (пиксели + `generation`) и +`InputSink` (VT-байты). Отсюда host-тесты без ядра и без `/dev/vtfb1`: +`tests/kernel_session.rs` (15 тестов) гоняет generation-гейт, блит +1:1/downscale/letterbox, `invalidate`-перерисовку, short frame, `ENODEV`/IO +ошибки, кодирование клавиш, `FileInput`, `read()`-fallback на обычном файле, +рендер сообщения, `--help`, откат на pipe-сессию при отсутствии устройств и +честную ошибку «поверхность есть, композитора нет». Плюс 8 unit-тестов +разбора заголовка и раскладки в `src/kernelsession.rs`. + +### Не входит в этот этап (честно) + +* нет PTY/`struct termios`, нет `TIOCGWINSZ`/SIGWINCH — размер сессии знает + только ядро, окно его не сообщает; +* нет terminal job-control: `Ctrl+Z` — байт в `/dev/vtinput1`, а знает о нём + kernel-shell; +* поверхность не несёт DEC-режимов → стрелки всегда normal, bracketed paste и + mouse-reporting из окна не включаются; +* одна сессия на окно; второй клиент увидит ту же поверхность; +* scrollback и selection остаются в ядре: колесо и протяжка мышью в окно не + транслируются (у клиента нет сетки, чтобы их применить); +* live-прогон в QEMU не выполнялся: kernel-сторона контракта реализуется в + параллельной ветке. Проверено: mock-устройства, `read()`-fallback на файле, + отказы устройств/композитора, `--help`, статическая musl-сборка. + ## Kernel console shared surface ABI v1 Реализовано в kernel (`/dev/vtconsole0`, `/dev/vtinput`; см. @@ -578,11 +737,13 @@ Kernel-side проверка (после реализации): boot-тест п без частичных damage; `/dev/vtinput` переводит байты в PS/2-скан-коды shell (см. `docs/desktop-b.md` §5.4 — UTF-8 > ASCII пока отбрасывается). `kernel/src/**` этим крейтом не тронут. -* **Нет PTY/termios/job-control.** Оконная сессия — процесс-shell за двумя - pipe'ами: нет управляющего терминала, `TIOCGWINSZ`, SIGWINCH, Ctrl+Z и - сигналов реальному потомку; `Ctrl+C` доставляется байтом. Shell внутри сессии — - встроенный минимальный userspace-shell (см. «Оконная shell-сессия»), а не - kernel-shell и не `/bin/sh` (на demo-образе его нет). +* **Нет PTY/termios/job-control.** У режима kernel-session управляющего + терминала в userspace нет вообще: shell, его эхо и его размер живут в ядре, + `Ctrl+C`/`Ctrl+Z` уходят байтами в `/dev/vtinput1`. У fallback-режима + (`--pipe-shell`, `--vt` + `--socket`) — процесс-shell за двумя pipe'ами: нет + `TIOCGWINSZ`, SIGWINCH и сигналов реальному потомку. Shell там — встроенный + минимальный userspace-shell (`help/ls/cd/pwd/echo/cat/uname/clear/exit`), а + не kernel-shell и не `/bin/sh` (на demo-образе его нет). * **Нет real framebuffer/evdev backend.** Клиент рисует в RGBA и отправляет кадры по сокету; `/dev/fb0` и `/dev/input/event0` — следующий шаг server/ desktop-ветки. @@ -596,9 +757,14 @@ Kernel-side проверка (после реализации): boot-тест п sixel/kitty graphics/OSC 1337 не поддерживаются. * **PNG без компрессии** — файлы большие; это тестовый формат, не формат протокола. -* **Не проверено на реальном железе/QEMU**: только host-тесты и статическая - musl-сборка. Интеграция с `pagh-desktop`/kernel VT требует прогона в - QEMU/на NVIDIA-хосте после появления device-ов. +* **Kernel-session не проверен live.** Клиент реализует зафиксированный + контракт (`/dev/vtfb1` ioctl `0x4700`/mmap/generation, `/dev/vtinput1`), но + kernel-сторона пишется параллельно: PR-ядро в base ещё не содержит устройств, + поэтому прогон в QEMU не делался. Проверено на mock-устройствах, + `read()`-fallback'е (обычный файл с заголовком и пикселями) и статической + musl-сборке. Первый live-прогон должен подтвердить три вещи контракта: + `generation` растёт на flush, `mmap`-пиксели действительно видны клиенту, а + `ENODEV` после `exit` доходит до окна как «сессия завершена». ## Проверки @@ -607,11 +773,21 @@ Kernel-side проверка (после реализации): boot-тест п ```sh cd rust-apps/pagh-terminal cargo fmt --all -- --check -cargo test # 120 host tests (60 unit + 60 integration) +cargo test # 159 host tests (80 unit + 79 integration) python3 tools/gen_font.py --check --allow-clip tools/build-static.sh # ELF static-pie x86_64-musl, no INTERP +# то же самое из корня репозитория: +tools/build-rust-app.sh rust-apps/pagh-terminal ``` +Раскладка 159 тестов: 80 unit (lib, включая 8 для `kernelsession`), 15 +`tests/kernel_session.rs` (mock-устройства и `read()`-fallback), 7 +`tests/headless_cli.rs`, 28 `tests/parser_golden.rs`, 1 `tests/pdp_e2e.rs`, 6 +`tests/protocol_client.rs`, 9 `tests/render_png.rs`, 4 +`tests/shell_session.rs`, 1 `tests/shm_e2e.rs`, 8 `tests/vtconsole_abi.rs`. +E2E `pdp_e2e`/`shm_e2e`/`headless_cli` теперь явно просят `--demo-shell`: они +проверяют демо/ShmSurface-путь, а не kernel-устройства, которых на хосте нет. + `--allow-clip` нужен генератору для 205 глифов, у которых антиалиасный край выходит за 8 px (в основном широкие латинские/кириллические буквы); это осознанно: клип в 1 px лучше, чем потеря покрытия. `--check` без флага From 5a6bf18265742d11083bf20cfc477a4aa5f7107a Mon Sep 17 00:00:00 2001 From: pagh-agent Date: Sat, 21 Nov 2026 15:19:59 +0300 Subject: [PATCH 03/12] terminal: log the kernel surface mapping and per-frame generation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Attaching to a kernel session is invisible on the wire: the client blits pixels and forwards bytes, so a live run has nothing to grep unless the client says what it did. Two lines close that gap, and the guest console forwards a process's stderr to the serial log, which is where live evidence is read from. On open, the surface path now prints how the pixels were obtained: pagh-terminal: kernel surface /dev/vtfb1: mmap 3145728 bytes PROT_READ|MAP_SHARED (ioctl 0x4700 1024x768 stride 4096 bpp 32) That distinguishes the mmap path (contract primary) from the read() fallback, whose existing "mmap of … unavailable (…); falling back to read() snapshots" line stays the counterpart. Without it a green window only proved that *some* source worked, not which one. `--vt-trace` logs every drawn frame with its kernel generation: pagh-terminal: kernel frame generation 42 drawn Off by default (a full-screen editor repaints a lot, and serial is 115200 baud), enabled per run for integration evidence: the generation numbers, in order, are the proof that the frame gate follows the kernel's flushes rather than a frozen or redundant repaint. The equivalent env var PAGH_TERMINAL_KERNEL_TRACE still works for hosts that can set it. No behaviour change: the drawing path, gate and error handling are untouched; the help/TERMINAL.md document both diagnostics, and the help test asserts the flag is listed. --- rust-apps/pagh-terminal/TERMINAL.md | 24 ++++++++++++++++++- .../pagh-terminal/src/bin/pagh-terminal.rs | 13 ++++++++-- .../src/bin/pagh-terminal/devfs.rs | 13 ++++++++-- .../pagh-terminal/tests/kernel_session.rs | 1 + 4 files changed, 46 insertions(+), 5 deletions(-) diff --git a/rust-apps/pagh-terminal/TERMINAL.md b/rust-apps/pagh-terminal/TERMINAL.md index c3ed9ee9..772cb521 100644 --- a/rust-apps/pagh-terminal/TERMINAL.md +++ b/rust-apps/pagh-terminal/TERMINAL.md @@ -76,7 +76,10 @@ bare-metal target, поэтому для host-сборки std пересоби Устройства kernel-session переопределяются `--vt-fb` (по умолчанию `/dev/vtfb1`) и `--vt-input` (по умолчанию `/dev/vtinput1` для этого режима и -`/dev/vtinput` для `--vt`/`--mirror-vt`). +`/dev/vtinput` для `--vt`/`--mirror-vt`). `--vt-trace` печатает каждый +отрисованный кадр с его `generation`: в гостевой консоли эти строки попадают в +serial-лог, чем live-прогон доказывает, что поверхность действительно +обновляется. ## Архитектура @@ -501,6 +504,25 @@ application cursor, bracketed paste, mouse) из неё не наблюдаем делать отдельным UI ввода, которого в v1 нет. Пауза перед закрытием нужна, чтобы сообщение успели прочитать, а не чтобы спрятать конец сессии. +### Диагностика live-прогона + +При открытии поверхности клиент печатает одну строку о том, **как** получены +пиксели, и с какой геометрией: + +```text +pagh-terminal: kernel surface /dev/vtfb1: mmap 3145728 bytes PROT_READ|MAP_SHARED (ioctl 0x4700 1024x768 stride 4096 bpp 32) +pagh-terminal: kernel session 1024x768 (stride 4096, generation 7) on /dev/vtfb1 +pagh-terminal: kernel session connected (client 3, screen 1280x800) +``` + +`read()`-fallback вместо первой строки печатает `mmap of … unavailable (…); +falling back to read() snapshots`, так что путь получения пикселей виден в логе +без отладчика. С `--vt-trace` каждый отрисованный кадр печатает +`kernel frame generation N drawn`, а завершение сессии — +`kernel session ended (the shell exited); window closed`. Гостевая консоль +форвардит stderr процесса в serial-лог, поэтому все эти строки — evidence для +live-интеграции (см. `.cache/pagh-agent-notes/q147-live/serial.log`). + ### Тестируемость `lib.rs` объявляет `#![forbid(unsafe_code)]`, поэтому `mmap`/`ioctl` живут diff --git a/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs b/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs index 3a11ad8f..d2adca8a 100644 --- a/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs +++ b/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs @@ -74,6 +74,8 @@ struct Args { vt_input: Option, /// Pixel surface of the kernel shell session (default `/dev/vtfb1`). vt_fb: String, + /// Log every drawn kernel frame (generation evidence for live runs). + vt_trace: bool, size: (u32, u32), cols: Option, rows: Option, @@ -116,6 +118,7 @@ impl Default for Args { vt: None, vt_input: None, vt_fb: KERNEL_FB.to_string(), + vt_trace: false, size: (900, 600), cols: None, rows: None, @@ -1344,7 +1347,10 @@ fn run_kernel_session(args: &Args, socket: &str) -> Result<(), String> { let mut dirty = true; let mut last_commit = Instant::now(); let mut input_error_reported = false; - let trace = std::env::var_os("PAGH_TERMINAL_KERNEL_TRACE").is_some(); + // `--vt-trace` (или переменная окружения) печатает каждый отрисованный + // кадр: в гостевой консоли это serial-доказательство того, что generation + // растёт с выводом сессии, а не «кадр застыл». + let trace = args.vt_trace || std::env::var_os("PAGH_TERMINAL_KERNEL_TRACE").is_some(); loop { // 1. Кадр сессии: перерисовываем окно только когда ядро опубликовало @@ -1354,7 +1360,7 @@ fn run_kernel_session(args: &Args, socket: &str) -> Result<(), String> { match frame.draw_if_changed(canvas, &theme) { Ok(Draw::Drawn { generation }) => { if trace { - eprintln!("pagh-terminal: kernel frame generation {generation}"); + eprintln!("pagh-terminal: kernel frame generation {generation} drawn"); } dirty = true; } @@ -1676,6 +1682,7 @@ fn parse_args>(mut args: I) -> Result { "--vt" => out.vt = Some(next_value(&mut args, "--vt")?), "--vt-input" => out.vt_input = Some(next_value(&mut args, "--vt-input")?), "--vt-fb" => out.vt_fb = next_value(&mut args, "--vt-fb")?, + "--vt-trace" => out.vt_trace = true, "--size" => out.size = parse_size(&next_value(&mut args, "--size")?)?, "--cols" => out.cols = Some(parse_usize(&next_value(&mut args, "--cols")?)?), "--rows" => out.rows = Some(parse_usize(&next_value(&mut args, "--rows")?)?), @@ -1777,6 +1784,8 @@ WINDOW (default with --socket): KERNEL SHELL SESSION only, and simulates nothing. --vt-fb PATH session pixel surface (default /dev/vtfb1) --vt-input PATH session input device (default /dev/vtinput1) + --vt-trace log every drawn frame (its kernel generation) to stderr; + the guest console forwards that to the serial log If the devices are missing (kernel without the session surface) the window says so on stderr and falls back to the private userspace shell session. If the devices exist but fail, the window shows the honest error and exits; it diff --git a/rust-apps/pagh-terminal/src/bin/pagh-terminal/devfs.rs b/rust-apps/pagh-terminal/src/bin/pagh-terminal/devfs.rs index 0183c0c6..9051ddc5 100644 --- a/rust-apps/pagh-terminal/src/bin/pagh-terminal/devfs.rs +++ b/rust-apps/pagh-terminal/src/bin/pagh-terminal/devfs.rs @@ -62,7 +62,7 @@ pub fn open_frame_source(path: &str) -> Result, OpenError> ))) } }; - match MmapSurface::new(file) { + match MmapSurface::new(file, path) { Ok(surface) => Ok(Box::new(surface)), Err(reason) => { eprintln!( @@ -87,7 +87,7 @@ struct MmapSurface { } impl MmapSurface { - fn new(file: File) -> Result { + fn new(file: File, path: &str) -> Result { let info = query_info(&file) .map_err(|error| format!("ioctl 0x{VTFB_IOCTL_GET_INFO:04x}: {error}"))?; let len = info.pixels_len(); @@ -113,6 +113,15 @@ impl MmapSurface { io::Error::last_os_error() )); } + // Одна строка на открытие: по ней видно, что поверхность получена + // именно общим отображением (а не read()-снимками), и какая геометрия + // объявлена ядром. В гостевой консоли она попадает в serial-лог, то + // есть служит доказательством live-интеграции без отладчика. + eprintln!( + "pagh-terminal: kernel surface {path}: mmap {len} bytes PROT_READ|MAP_SHARED \ + (ioctl 0x{VTFB_IOCTL_GET_INFO:04x} {}x{} stride {} bpp {})", + info.width, info.height, info.stride, info.bpp + ); Ok(MmapSurface { file, base: base as *mut u8, diff --git a/rust-apps/pagh-terminal/tests/kernel_session.rs b/rust-apps/pagh-terminal/tests/kernel_session.rs index 9ecc3a1b..d30a997f 100644 --- a/rust-apps/pagh-terminal/tests/kernel_session.rs +++ b/rust-apps/pagh-terminal/tests/kernel_session.rs @@ -425,6 +425,7 @@ fn help_names_the_kernel_session_mode_and_its_devices() { "/dev/vtfb1", "/dev/vtinput1", "--vt-fb", + "--vt-trace", "--pipe-shell", "--demo-shell", "no PTY/termios", From 476f13df388088a739aba97d5f313d7714671a29 Mon Sep 17 00:00:00 2001 From: pagh-agent Date: Sat, 21 Nov 2026 15:39:21 +0300 Subject: [PATCH 04/12] terminal: route kernel-session diagnostics through --log-file, not stderr MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Live integration found the wall the desktop puts in front of its own children. The compositor starts applications with --launch-target in a BACKGROUND console process group, and this kernel enables TOSTOP by default, so the app's first write to stderr raises SIGTTOU and the job is stopped before it can map its surface (serial: "stopped by pgid 7 (foreground 1) -> SIGTTOU + EINTR"). A client launched the way the shipped desktop launches it therefore cannot report anything on stderr — including the kernel-session attach lines. `--log-file PATH` moves every diagnostic of the mode (surface mapping, ioctl geometry, connection, per-frame generation with --vt-trace, session end, device failure) into a file opened in append mode, so a relaunch adds to the previous run instead of erasing its evidence. Without the flag the sink is stderr exactly as before, so shell-launched runs and the existing tests are unchanged. The surface helper no longer prints: devfs returns a note ("kernel surface … mmap … PROT_READ|MAP_SHARED (ioctl 0x4700 …)") and the binary decides where it goes, because the sink is client policy and the device layer must stay a thin unsafe shim. Also records the second live finding in TERMINAL.md, since both are properties of the ABI rather than of this client: window input only reaches the session when the console has no foreground compat process (vtinput::write_session hands bytes to FG_PID's stdin otherwise), so the terminal must be started by the compositor — not typed as a shell job; and such a background child must log to a file because of TOSTOP. Tests: --log-file case (missing devices + fake compositor: the fallback line lands in the file, not on stderr), help lists the flag; 170 host tests green. --- rust-apps/pagh-terminal/TERMINAL.md | 20 ++- .../pagh-terminal/src/bin/pagh-terminal.rs | 153 +++++++++++++----- .../src/bin/pagh-terminal/devfs.rs | 61 ++++--- .../pagh-terminal/tests/kernel_session.rs | 50 ++++++ 4 files changed, 223 insertions(+), 61 deletions(-) diff --git a/rust-apps/pagh-terminal/TERMINAL.md b/rust-apps/pagh-terminal/TERMINAL.md index 772cb521..713f6e7d 100644 --- a/rust-apps/pagh-terminal/TERMINAL.md +++ b/rust-apps/pagh-terminal/TERMINAL.md @@ -523,6 +523,14 @@ falling back to read() snapshots`, так что путь получения п форвардит stderr процесса в serial-лог, поэтому все эти строки — evidence для live-интеграции (см. `.cache/pagh-agent-notes/q147-live/serial.log`). +`--log-file PATH` уводит всю диагностику режима из stderr в файл. Это не +косметика: desktop запускает приложения через `--launch-target` в **фоновой** +группе консоли, а TOSTOP в этом ядре включён по умолчанию — первая же строка в +stderr останавливает клиента `SIGTTOU` (в serial: `stopped by pgid N +(foreground 1) -> SIGTTOU + EINTR`). Поэтому запуск композитором идёт с +`--log-file /mnt/…`, а строки потом читаются из файла (например `cat` из +shell). + ### Тестируемость `lib.rs` объявляет `#![forbid(unsafe_code)]`, поэтому `mmap`/`ioctl` живут @@ -544,7 +552,17 @@ live-интеграции (см. `.cache/pagh-agent-notes/q147-live/serial.log`) kernel-shell; * поверхность не несёт DEC-режимов → стрелки всегда normal, bracketed paste и mouse-reporting из окна не включаются; -* одна сессия на окно; второй клиент увидит ту же поверхность; +* одна сессия на окно; второй клиент увидит ту же поверхность (и получит + `duplicate window`/`not owner`, если возьмёт занятый `--window-id`); +* **ввод окна требует, чтобы консоль не имела foreground-совместимого + процесса.** `vtinput::write_session` при `FG_PID != 0` отдаёт байты в stdin + этого процесса: окно, запущенное прямо из kernel-shell как foreground-задача + (`rust /mnt/pagh-terminal …`), выглядит живым, но его клавиатура уходит в + stdin самого клиента. Штатный путь — запуск композитором (`--launch-target` + + hotkey), как в `desktop-autorun`; +* **фоновый запуск и stderr.** Клиент, запущенный композитором, находится в + фоновой группе консоли; TOSTOP останавливает его на первой записи в stderr, + поэтому такой запуск обязан использовать `--log-file`; * scrollback и selection остаются в ядре: колесо и протяжка мышью в окно не транслируются (у клиента нет сетки, чтобы их применить); * live-прогон в QEMU не выполнялся: kernel-сторона контракта реализуется в diff --git a/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs b/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs index d2adca8a..2ee7b3db 100644 --- a/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs +++ b/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs @@ -52,6 +52,50 @@ use pagh_ui::geom::Rect; const VERSION: &str = "0.1.0"; +/// Куда писать диагностику окна. +/// +/// Обычный путь — stderr (запуск из shell). Но desktop запускает приложения +/// через `--launch-target` из **фоновой** группы консоли, а TOSTOP в этом ядре +/// включён по умолчанию: первая же строка в stderr останавливает клиента +/// сигналом SIGTTOU (в serial это видно как `stopped by pgid N (foreground 1) +/// -> SIGTTOU + EINTR`). Поэтому `--log-file PATH` уводит все строки в файл +/// (ext2), а не в консоль. +struct Diag { + file: Option, +} + +impl Diag { + fn new(path: Option<&std::path::Path>) -> Result { + match path { + Some(path) => { + // Append, не truncate: перезапуск окна (и новая сессия ядра) не + // должен стирать строки предыдущего запуска — именно их читают + // как evidence. + let file = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(path) + .map_err(|e| format!("{}: {e}", path.display()))?; + Ok(Diag { file: Some(file) }) + } + None => Ok(Diag { file: None }), + } + } + + /// Одна строка диагностики (с префиксом `pagh-terminal:`). + fn line(&mut self, text: &str) { + use std::io::Write; + match self.file.as_mut() { + // Файл — не tty: SIGTTOU здесь невозможен, а строка должна быть + // видна сразу (`cat` во время работы клиента). + Some(file) => { + let _ = writeln!(file, "pagh-terminal: {text}"); + } + None => eprintln!("pagh-terminal: {text}"), + } + } +} + /// Kernel shell-session pixel surface (mode default). const KERNEL_FB: &str = "/dev/vtfb1"; /// Kernel shell-session input device. @@ -76,6 +120,8 @@ struct Args { vt_fb: String, /// Log every drawn kernel frame (generation evidence for live runs). vt_trace: bool, + /// Diagnostics sink: a file instead of stderr (desktop-launched apps). + log_file: Option, size: (u32, u32), cols: Option, rows: Option, @@ -119,6 +165,7 @@ impl Default for Args { vt_input: None, vt_fb: KERNEL_FB.to_string(), vt_trace: false, + log_file: None, size: (900, 600), cols: None, rows: None, @@ -1271,46 +1318,65 @@ fn run_shell_session(args: &Args, socket: &str) -> Result<(), String> { fn run_kernel_session(args: &Args, socket: &str) -> Result<(), String> { let fb_path = args.vt_fb.as_str(); let input_path = args.kernel_input(); + // Все строки режима — через `Diag`: при запуске композитором они уходят в + // `--log-file`, иначе первая же строка в stderr остановила бы клиента + // SIGTTOU (фоновая группа консоли + TOSTOP). + let mut diag = Diag::new(args.log_file.as_deref())?; + macro_rules! note { + ($($arg:tt)*) => { + diag.line(&format!($($arg)*)) + }; + } - let source = match devfs::open_frame_source(fb_path) { - Ok(source) => source, + let opened = match devfs::open_frame_source(fb_path) { + Ok(opened) => opened, Err(devfs::OpenError::Missing) => { - eprintln!( - "pagh-terminal: {fb_path} is not present (kernel without the shell-session \ + note!( + "{fb_path} is not present (kernel without the shell-session \ surface); falling back to the private userspace shell session" ); return run_shell_session(args, socket); } - Err(devfs::OpenError::Failed(reason)) => return fail_with_notice(args, socket, &reason), + Err(devfs::OpenError::Failed(reason)) => { + return fail_with_notice(args, socket, &mut diag, &reason) + } }; + note!("{}", opened.note); let key_sink = match FileInput::open(input_path) { Ok(sink) => sink, Err(error) if is_missing_device(&error) => { - eprintln!( - "pagh-terminal: {input_path} is not present (kernel without the shell-session \ + note!( + "{input_path} is not present (kernel without the shell-session \ input); falling back to the private userspace shell session" ); return run_shell_session(args, socket); } - Err(error) => return fail_with_notice(args, socket, &format!("{input_path}: {error}")), + Err(error) => { + return fail_with_notice(args, socket, &mut diag, &format!("{input_path}: {error}")) + } }; - let mut frame = match KernelFrame::open(source) { + let mut frame = match KernelFrame::open(opened.source) { Ok(frame) => frame, - Err(error) => return fail_with_notice(args, socket, &error.message()), + Err(error) => return fail_with_notice(args, socket, &mut diag, &error.message()), }; let info = frame.info(); - eprintln!( - "pagh-terminal: kernel session {}x{} (stride {}, generation {}) on {fb_path}", - info.width, info.height, info.stride, info.generation + note!( + "kernel session {}x{} (stride {}, generation {}) on {fb_path}", + info.width, + info.height, + info.stride, + info.generation ); let mut client = SurfaceClient::connect(socket).map_err(|e| format!("{socket}: {e}"))?; let welcome = client .handshake("pagh-terminal", Duration::from_secs(5)) .map_err(|e| format!("handshake: {e}"))?; - eprintln!( - "pagh-terminal: kernel session connected (client {}, screen {}x{})", - welcome.client_id, welcome.screen_width, welcome.screen_height + note!( + "kernel session connected (client {}, screen {}x{})", + welcome.client_id, + welcome.screen_width, + welcome.screen_height ); client .create_window(args.window_id, args.size.0, args.size.1, &args.title) @@ -1330,7 +1396,7 @@ fn run_kernel_session(args: &Args, socket: &str) -> Result<(), String> { let mut shm = match client.enable_shm(width, height) { Ok(shm) => shm, Err(error) => { - eprintln!("pagh-terminal: shm unavailable ({error}); full frames"); + note!("shm unavailable ({error}); full frames"); None } }; @@ -1360,7 +1426,7 @@ fn run_kernel_session(args: &Args, socket: &str) -> Result<(), String> { match frame.draw_if_changed(canvas, &theme) { Ok(Draw::Drawn { generation }) => { if trace { - eprintln!("pagh-terminal: kernel frame generation {generation} drawn"); + note!("kernel frame generation {generation} drawn"); } dirty = true; } @@ -1369,6 +1435,7 @@ fn run_kernel_session(args: &Args, socket: &str) -> Result<(), String> { return end_kernel_session( &mut client, &mut shm, + &mut diag, &theme, width, height, @@ -1384,8 +1451,15 @@ fn run_kernel_session(args: &Args, socket: &str) -> Result<(), String> { "", "Close this window and relaunch pagh-terminal to retry.", ]; - let _ = - end_kernel_session(&mut client, &mut shm, &theme, width, height, &lines); + let _ = end_kernel_session( + &mut client, + &mut shm, + &mut diag, + &theme, + width, + height, + &lines, + ); return Err(message); } } @@ -1492,15 +1566,13 @@ fn run_kernel_session(args: &Args, socket: &str) -> Result<(), String> { // Сессия закончилась между кадром и нажатием: следующий // опрос поверхности вернёт ENODEV и закроет окно честно. if !input_error_reported { - eprintln!( - "pagh-terminal: session ended while forwarding a key ({error})" - ); + note!("session ended while forwarding a key ({error})"); input_error_reported = true; } } Err(error) => { if !input_error_reported { - eprintln!("pagh-terminal: cannot write {input_path}: {error}"); + note!("cannot write {input_path}: {error}"); input_error_reported = true; } } @@ -1514,19 +1586,11 @@ fn run_kernel_session(args: &Args, socket: &str) -> Result<(), String> { } Event::Input(InputEvent::Motion { .. }) => {} Event::Close { reason, .. } => { - eprintln!( - "pagh-terminal: server closed the window ({})", - close_name(reason) - ); + note!("server closed the window ({})", close_name(reason)); return Ok(()); } Event::Error { code, message } => { - eprintln!( - "pagh-terminal: server error {} ({}): {}", - error_name(code), - code, - message - ); + note!("server error {} ({}): {}", error_name(code), code, message); } Event::Ping(_) | Event::Pong(_) => {} } @@ -1567,6 +1631,7 @@ fn canvas_mut<'a>( fn end_kernel_session( client: &mut SurfaceClient, shm: &mut Option, + diag: &mut Diag, theme: &Theme, width: u32, height: u32, @@ -1574,7 +1639,7 @@ fn end_kernel_session( ) -> Result<(), String> { show_notice(client, shm, theme, width, height, lines)?; let _ = client.close(); - eprintln!("pagh-terminal: kernel session ended (the shell exited); window closed"); + diag.line("kernel session ended (the shell exited); window closed"); Ok(()) } @@ -1602,8 +1667,13 @@ fn show_notice( /// Окно создаётся только чтобы сказать правду (запуск из шелла без дисплея /// просто получит ошибку в stderr). Никакого отката в демо-шелл: пользователь /// должен видеть, что сессии ядра нет. -fn fail_with_notice(args: &Args, socket: &str, reason: &str) -> Result<(), String> { - eprintln!("pagh-terminal: kernel session unavailable: {reason}"); +fn fail_with_notice( + args: &Args, + socket: &str, + diag: &mut Diag, + reason: &str, +) -> Result<(), String> { + diag.line(&format!("kernel session unavailable: {reason}")); let mut client = SurfaceClient::connect(socket).map_err(|e| format!("{socket}: {e}"))?; client .handshake("pagh-terminal", Duration::from_secs(5)) @@ -1683,6 +1753,9 @@ fn parse_args>(mut args: I) -> Result { "--vt-input" => out.vt_input = Some(next_value(&mut args, "--vt-input")?), "--vt-fb" => out.vt_fb = next_value(&mut args, "--vt-fb")?, "--vt-trace" => out.vt_trace = true, + "--log-file" => { + out.log_file = Some(PathBuf::from(next_value(&mut args, "--log-file")?)) + } "--size" => out.size = parse_size(&next_value(&mut args, "--size")?)?, "--cols" => out.cols = Some(parse_usize(&next_value(&mut args, "--cols")?)?), "--rows" => out.rows = Some(parse_usize(&next_value(&mut args, "--rows")?)?), @@ -1784,8 +1857,12 @@ WINDOW (default with --socket): KERNEL SHELL SESSION only, and simulates nothing. --vt-fb PATH session pixel surface (default /dev/vtfb1) --vt-input PATH session input device (default /dev/vtinput1) - --vt-trace log every drawn frame (its kernel generation) to stderr; + --vt-trace log every drawn frame (its kernel generation); the guest console forwards that to the serial log + --log-file PATH send client diagnostics to PATH instead of stderr. Needed + when the desktop launches the app (`--launch-target`): such + a child runs in a BACKGROUND console group and the kernel's + TOSTOP stops it with SIGTTOU on the first stderr write If the devices are missing (kernel without the session surface) the window says so on stderr and falls back to the private userspace shell session. If the devices exist but fail, the window shows the honest error and exits; it diff --git a/rust-apps/pagh-terminal/src/bin/pagh-terminal/devfs.rs b/rust-apps/pagh-terminal/src/bin/pagh-terminal/devfs.rs index 9051ddc5..f7d7b201 100644 --- a/rust-apps/pagh-terminal/src/bin/pagh-terminal/devfs.rs +++ b/rust-apps/pagh-terminal/src/bin/pagh-terminal/devfs.rs @@ -38,6 +38,17 @@ extern "C" { fn munmap(addr: *mut c_void, len: usize) -> c_int; } +/// Открытая поверхность плюс одна строка о том, **как** получены пиксели. +/// +/// Строку пишет вызывающий (bin), а не этот модуль: приложение может быть +/// запущено композитором в фоновой группе консоли, где TOSTOP останавливает +/// первого же писателя в stderr, поэтому место записи — политика клиента +/// (`--log-file`), а не устройство. +pub struct OpenedSurface { + pub source: Box, + pub note: String, +} + /// Почему устройство не открылось. pub enum OpenError { /// Устройства нет в системе (`ENOENT`): ядро без `/dev/vtfb1`. @@ -52,7 +63,7 @@ pub enum OpenError { /// фатальным: контракт разрешает `read()`-снимки, поэтому клиент деградирует на /// них и говорит об этом в stderr. Отсутствие самого устройства — не деградация, /// а [`OpenError::Missing`], по которому вызывающий откатывается на pipe-сессию. -pub fn open_frame_source(path: &str) -> Result, OpenError> { +pub fn open_frame_source(path: &str) -> Result { let file = match File::open(path) { Ok(file) => file, Err(error) if error.kind() == io::ErrorKind::NotFound => return Err(OpenError::Missing), @@ -63,16 +74,19 @@ pub fn open_frame_source(path: &str) -> Result, OpenError> } }; match MmapSurface::new(file, path) { - Ok(surface) => Ok(Box::new(surface)), - Err(reason) => { - eprintln!( - "pagh-terminal: mmap of {path} unavailable ({reason}); falling back to read() snapshots" - ); - match ReadFrameSource::open(path) { - Ok(source) => Ok(Box::new(source)), - Err(error) => Err(OpenError::Failed(format!("{path}: {}", error.message()))), - } - } + Ok((surface, note)) => Ok(OpenedSurface { + source: Box::new(surface), + note, + }), + Err(reason) => match ReadFrameSource::open(path) { + Ok(source) => Ok(OpenedSurface { + source: Box::new(source), + note: format!( + "mmap of {path} unavailable ({reason}); falling back to read() snapshots" + ), + }), + Err(error) => Err(OpenError::Failed(format!("{path}: {}", error.message()))), + }, } } @@ -87,7 +101,7 @@ struct MmapSurface { } impl MmapSurface { - fn new(file: File, path: &str) -> Result { + fn new(file: File, path: &str) -> Result<(MmapSurface, String), String> { let info = query_info(&file) .map_err(|error| format!("ioctl 0x{VTFB_IOCTL_GET_INFO:04x}: {error}"))?; let len = info.pixels_len(); @@ -115,19 +129,22 @@ impl MmapSurface { } // Одна строка на открытие: по ней видно, что поверхность получена // именно общим отображением (а не read()-снимками), и какая геометрия - // объявлена ядром. В гостевой консоли она попадает в serial-лог, то - // есть служит доказательством live-интеграции без отладчика. - eprintln!( - "pagh-terminal: kernel surface {path}: mmap {len} bytes PROT_READ|MAP_SHARED \ + // объявлена ядром. Клиент пишет её в свой лог, поэтому live-прогон + // доказывает путь получения пикселей без отладчика. + let note = format!( + "kernel surface {path}: mmap {len} bytes PROT_READ|MAP_SHARED \ (ioctl 0x{VTFB_IOCTL_GET_INFO:04x} {}x{} stride {} bpp {})", info.width, info.height, info.stride, info.bpp ); - Ok(MmapSurface { - file, - base: base as *mut u8, - len, - info, - }) + Ok(( + MmapSurface { + file, + base: base as *mut u8, + len, + info, + }, + note, + )) } } diff --git a/rust-apps/pagh-terminal/tests/kernel_session.rs b/rust-apps/pagh-terminal/tests/kernel_session.rs index d30a997f..b3e30c89 100644 --- a/rust-apps/pagh-terminal/tests/kernel_session.rs +++ b/rust-apps/pagh-terminal/tests/kernel_session.rs @@ -426,6 +426,7 @@ fn help_names_the_kernel_session_mode_and_its_devices() { "/dev/vtinput1", "--vt-fb", "--vt-trace", + "--log-file", "--pipe-shell", "--demo-shell", "no PTY/termios", @@ -542,6 +543,55 @@ fn missing_kernel_devices_fall_back_to_the_pipe_shell_session() { let _ = std::fs::remove_dir_all(&dir); } +/// Диагностика режима должна уметь уходить в файл: desktop запускает клиента +/// `--launch-target` в фоновой группе консоли, где TOSTOP останавливает первую +/// же запись в stderr (SIGTTOU). `--log-file` — штатный путь для такого запуска. +#[test] +fn log_file_receives_the_diagnostics_instead_of_stderr() { + let dir = temp_dir("logfile"); + let socket = dir.join("desktop.sock"); + let (server, ready) = spawn_fake_desktop(&socket); + let log = dir.join("client.log"); + let missing_fb = dir.join("no-such-vtfb1"); + let missing_input = dir.join("no-such-vtinput1"); + + let out = Command::new(binary()) + .args(["--socket"]) + .arg(&socket) + .args(["--size", "320x200"]) + .arg("--vt-fb") + .arg(&missing_fb) + .arg("--vt-input") + .arg(&missing_input) + .arg("--log-file") + .arg(&log) + .stdout(Stdio::null()) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + let text = std::fs::read_to_string(&log).expect("log file"); + assert!( + text.contains("is not present") && text.contains("falling back"), + "the kernel-session note must go to the log file: {text:?}" + ); + assert!( + text.starts_with("pagh-terminal: "), + "log lines keep the client prefix: {text:?}" + ); + assert!( + !stderr.contains("is not present"), + "with --log-file that line must not reach stderr: {stderr:?}" + ); + assert!(ready.recv_timeout(Duration::from_secs(10)).is_ok()); + server.join().expect("fake compositor"); + assert!( + out.status.success(), + "fallback client must exit cleanly: {:?}", + out.status + ); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn a_regular_file_surface_uses_read_fallback_and_reports_a_missing_compositor() { let dir = temp_dir("readfallback"); From 5fcf1fd8259ddf5f3804eda656541f31d173dc59 Mon Sep 17 00:00:00 2001 From: pagh-agent Date: Sat, 21 Nov 2026 15:53:00 +0300 Subject: [PATCH 05/12] terminal: fatal errors follow --log-file too MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The desktop launches its applications as background console jobs, so a write to stderr stops them with SIGTTOU. The `--log-file` sink covered the kernel-session runtime, but not the failures that happen before it exists: an unknown argument (which is what a target with an extra `--connect` produces) exited through `eprintln!` and vanished into the TOSTOP stop — the window silently never appears and nothing anywhere says why. `report_fatal` now rescans the raw argv for `--log-file` and appends the fatal line there, falling back to stderr when the flag is absent or the file cannot be opened. Argv is used deliberately: the error may be a parse error, so the normal Args value may not exist yet. Test: `--no-such-flag --log-file F` exits 2 with the error inside F and nothing on stderr (17 kernel-session tests, 171 host tests green). --- rust-apps/pagh-terminal/TERMINAL.md | 3 +- .../pagh-terminal/src/bin/pagh-terminal.rs | 30 ++++++++++++++++++- .../pagh-terminal/tests/kernel_session.rs | 28 +++++++++++++++++ 3 files changed, 59 insertions(+), 2 deletions(-) diff --git a/rust-apps/pagh-terminal/TERMINAL.md b/rust-apps/pagh-terminal/TERMINAL.md index 713f6e7d..9ab6d2c0 100644 --- a/rust-apps/pagh-terminal/TERMINAL.md +++ b/rust-apps/pagh-terminal/TERMINAL.md @@ -523,7 +523,8 @@ falling back to read() snapshots`, так что путь получения п форвардит stderr процесса в serial-лог, поэтому все эти строки — evidence для live-интеграции (см. `.cache/pagh-agent-notes/q147-live/serial.log`). -`--log-file PATH` уводит всю диагностику режима из stderr в файл. Это не +`--log-file PATH` уводит всю диагностику режима (включая фатальные ошибки до +создания окна — например неизвестный аргумент) из stderr в файл. Это не косметика: desktop запускает приложения через `--launch-target` в **фоновой** группе консоли, а TOSTOP в этом ядре включён по умолчанию — первая же строка в stderr останавливает клиента `SIGTTOU` (в serial: `stopped by pgid N diff --git a/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs b/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs index 2ee7b3db..7858bc98 100644 --- a/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs +++ b/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs @@ -213,12 +213,40 @@ fn main() -> ExitCode { match run() { Ok(()) => ExitCode::SUCCESS, Err(error) => { - eprintln!("pagh-terminal: {error}"); + report_fatal(&error); ExitCode::from(2) } } } +/// Фатальная ошибка клиента: в stderr или в `--log-file`, если он задан. +/// +/// Запущенный композитором ребёнок живёт в **фоновой** группе консоли, где +/// TOSTOP останавливает его первым же `write` в stderr. Без этого сообщение не +/// увидел бы никто: приложение «молча не стартует». `--log-file` читается из +/// сырой argv, потому что ошибка может быть и ошибкой разбора аргументов. +fn report_fatal(error: &str) { + use std::io::Write; + let argv: Vec = std::env::args().skip(1).collect(); + let log_file = argv + .iter() + .position(|arg| arg == "--log-file") + .and_then(|index| argv.get(index + 1)) + .cloned(); + if let Some(path) = log_file { + if let Ok(mut file) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&path) + { + if writeln!(file, "pagh-terminal: {error}").is_ok() { + return; + } + } + } + eprintln!("pagh-terminal: {error}"); +} + fn run() -> Result<(), String> { let args = parse_args(std::env::args().skip(1))?; if args.help { diff --git a/rust-apps/pagh-terminal/tests/kernel_session.rs b/rust-apps/pagh-terminal/tests/kernel_session.rs index b3e30c89..ef733abc 100644 --- a/rust-apps/pagh-terminal/tests/kernel_session.rs +++ b/rust-apps/pagh-terminal/tests/kernel_session.rs @@ -592,6 +592,34 @@ fn log_file_receives_the_diagnostics_instead_of_stderr() { let _ = std::fs::remove_dir_all(&dir); } +/// Фатальная ошибка тоже обязана уходить в `--log-file`: у приложения, +/// запущенного композитором, запись в stderr останавливает его SIGTTOU, и +/// иначе сбой старта («неизвестный аргумент») не увидел бы никто. +#[test] +fn fatal_errors_go_to_the_log_file_when_one_is_given() { + let dir = temp_dir("fatal"); + let log = dir.join("client.log"); + let out = Command::new(binary()) + .args(["--no-such-flag"]) + .arg("--log-file") + .arg(&log) + .stdout(Stdio::null()) + .output() + .unwrap(); + assert_eq!(out.status.code(), Some(2), "unknown argument must be fatal"); + let text = std::fs::read_to_string(&log).expect("fatal error must land in the log file"); + assert!( + text.contains("unknown argument") && text.starts_with("pagh-terminal: "), + "unexpected log content: {text:?}" + ); + assert!( + !String::from_utf8_lossy(&out.stderr).contains("unknown argument"), + "the fatal line must not also hit stderr: {:?}", + String::from_utf8_lossy(&out.stderr) + ); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn a_regular_file_surface_uses_read_fallback_and_reports_a_missing_compositor() { let dir = temp_dir("readfallback"); From 449c6d4868d490d60276595e1425c77b43519a76 Mon Sep 17 00:00:00 2001 From: pagh-agent Date: Sat, 21 Nov 2026 16:09:12 +0300 Subject: [PATCH 06/12] terminal: keep earlier --log-file runs (O_APPEND is not implemented) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The guest's Linux layer accepts O_APPEND and ignores it, so every client that opened the diagnostics file wrote from offset 0. Two sequential launches of the terminal — exactly what the relaunch/respawn step does — therefore overwrote each other: the second client's lines landed on top of the first's, including the "kernel surface … mmap" line and the ENODEV end line. A live run read as one corrupted client instead of two. `Diag` and `report_fatal` now open the file and seek to End(0) explicitly, so appending does not depend on a flag this kernel does not honour. Test: two fatal runs against one file keep both "unknown argument" lines. 18 kernel-session tests, 172 host tests green. --- rust-apps/pagh-terminal/TERMINAL.md | 5 +++- .../pagh-terminal/src/bin/pagh-terminal.rs | 15 ++++++++--- .../pagh-terminal/tests/kernel_session.rs | 25 +++++++++++++++++++ 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/rust-apps/pagh-terminal/TERMINAL.md b/rust-apps/pagh-terminal/TERMINAL.md index 9ab6d2c0..23e725f0 100644 --- a/rust-apps/pagh-terminal/TERMINAL.md +++ b/rust-apps/pagh-terminal/TERMINAL.md @@ -524,7 +524,10 @@ falling back to read() snapshots`, так что путь получения п live-интеграции (см. `.cache/pagh-agent-notes/q147-live/serial.log`). `--log-file PATH` уводит всю диагностику режима (включая фатальные ошибки до -создания окна — например неизвестный аргумент) из stderr в файл. Это не +создания окна — например неизвестный аргумент) из stderr в файл. Файл +дописывается, а конец ищется явным `seek`: `O_APPEND` этот Linux-слой +принимает и игнорирует, поэтому без `seek` второй запуск затирал бы строки +первого — а они и есть evidence. Это не косметика: desktop запускает приложения через `--launch-target` в **фоновой** группе консоли, а TOSTOP в этом ядре включён по умолчанию — первая же строка в stderr останавливает клиента `SIGTTOU` (в serial: `stopped by pgid N diff --git a/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs b/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs index 7858bc98..cd0b9127 100644 --- a/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs +++ b/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs @@ -24,6 +24,7 @@ #[path = "pagh-terminal/devfs.rs"] mod devfs; +use std::io::Seek; use std::path::PathBuf; use std::process::ExitCode; use std::time::{Duration, Instant}; @@ -71,11 +72,17 @@ impl Diag { // Append, не truncate: перезапуск окна (и новая сессия ядра) не // должен стирать строки предыдущего запуска — именно их читают // как evidence. - let file = std::fs::OpenOptions::new() + let mut file = std::fs::OpenOptions::new() .create(true) - .append(true) + .write(true) .open(path) .map_err(|e| format!("{}: {e}", path.display()))?; + // `O_APPEND` этот Linux-слой не реализует (флаг принимается и + // игнорируется), поэтому конец файла ищется явно: иначе второй + // запуск клиента затирал бы строки первого — а именно они и есть + // evidence. + file.seek(std::io::SeekFrom::End(0)) + .map_err(|e| format!("{}: {e}", path.display()))?; Ok(Diag { file: Some(file) }) } None => Ok(Diag { file: None }), @@ -236,9 +243,11 @@ fn report_fatal(error: &str) { if let Some(path) = log_file { if let Ok(mut file) = std::fs::OpenOptions::new() .create(true) - .append(true) + .write(true) .open(&path) { + // Как и в `Diag::new`: без `O_APPEND` конец файла ищется вручную. + let _ = file.seek(std::io::SeekFrom::End(0)); if writeln!(file, "pagh-terminal: {error}").is_ok() { return; } diff --git a/rust-apps/pagh-terminal/tests/kernel_session.rs b/rust-apps/pagh-terminal/tests/kernel_session.rs index ef733abc..3cddea6b 100644 --- a/rust-apps/pagh-terminal/tests/kernel_session.rs +++ b/rust-apps/pagh-terminal/tests/kernel_session.rs @@ -595,6 +595,31 @@ fn log_file_receives_the_diagnostics_instead_of_stderr() { /// Фатальная ошибка тоже обязана уходить в `--log-file`: у приложения, /// запущенного композитором, запись в stderr останавливает его SIGTTOU, и /// иначе сбой старта («неизвестный аргумент») не увидел бы никто. +/// Второй запуск не должен затирать строки первого: `O_APPEND` в этом +/// Linux-слое не реализован, поэтому клиент ищет конец файла сам. +#[test] +fn the_log_file_keeps_earlier_runs() { + let dir = temp_dir("append"); + let log = dir.join("client.log"); + for _ in 0..2 { + let out = Command::new(binary()) + .args(["--no-such-flag"]) + .arg("--log-file") + .arg(&log) + .stdout(Stdio::null()) + .output() + .unwrap(); + assert_eq!(out.status.code(), Some(2)); + } + let text = std::fs::read_to_string(&log).expect("log file"); + assert_eq!( + text.matches("unknown argument").count(), + 2, + "both runs must be preserved (append, not overwrite): {text:?}" + ); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn fatal_errors_go_to_the_log_file_when_one_is_given() { let dir = temp_dir("fatal"); From 6369781120e651abb7f917617e79ff651cddf615 Mon Sep 17 00:00:00 2001 From: pagh-agent Date: Sat, 21 Nov 2026 18:45:25 +0300 Subject: [PATCH 07/12] terminal: restart the finished session in the same window MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `exit` in the kernel shell makes /dev/vtfb1 answer ENODEV, and the client used to answer that by closing the window and telling the user to relaunch. Relaunch is what produced the `duplicate window` blocker: the compositor still held the window id of the previous client when the new client asked for it, so a reopen could be refused even though the desktop looked empty. The window now outlives the session. On ENODEV the client draws the honest notice ("the shell session has ended — press Enter to start a new session in this window") and stays connected; the next key reopens /dev/vtinput1 and /dev/vtfb1. The kernel spawns a fresh session on the first open of either device, so the same window continues on a brand-new session — one `create`, one window id, no second client for the compositor to arbitrate. Plumbing: `FrameSource::respawn` / `InputSink::respawn` (defaults are no-ops or Ended, so mocks and non-device sinks keep working), implemented by `ReadFrameSource` (fresh open), `MmapSurface` (new open + mmap, old mapping unmapped, old fd closed) and `FileInput` (fresh open). `KernelFrame::respawn` resets the generation gate and forces a full blit; a failure is reported honestly and only then closes the window. Tests: a finished session restarts in the same canvas (fresh generation, Drawn again), the input device is reopened for the new session, and the ENODEV message names Enter instead of "relaunch". 174 host tests green. --- rust-apps/pagh-terminal/TERMINAL.md | 16 +-- .../pagh-terminal/src/bin/pagh-terminal.rs | 99 ++++++++++++++++--- .../src/bin/pagh-terminal/devfs.rs | 44 +++++++++ rust-apps/pagh-terminal/src/kernelsession.rs | 56 ++++++++++- .../pagh-terminal/tests/kernel_session.rs | 66 ++++++++++++- 5 files changed, 256 insertions(+), 25 deletions(-) diff --git a/rust-apps/pagh-terminal/TERMINAL.md b/rust-apps/pagh-terminal/TERMINAL.md index 23e725f0..190419a0 100644 --- a/rust-apps/pagh-terminal/TERMINAL.md +++ b/rust-apps/pagh-terminal/TERMINAL.md @@ -493,16 +493,19 @@ application cursor, bracketed paste, mouse) из неё не наблюдаем | ситуация | поведение | |---|---| -| `exit` в сессии → `ENODEV` | в окне: «the shell session has ended / relaunch to reconnect», пауза 1.5 с, окно закрывается | +| `exit` в сессии → `ENODEV` | плашка «the shell session has ended / Press Enter to start a new session in this window»; окно **остаётся**, Enter переоткрывает `vtfb1`/`vtinput1` и ядро поднимает новую сессию в том же окне | | `/dev/vtfb1` или `/dev/vtinput1` нет (`ENOENT`, старое ядро) | честная строка в stderr + откат на pipe-сессию (`--pipe-shell`-путь) | | устройство есть, но ioctl/mmap/read/write не работают | честное сообщение **в окне** + код возврата 2, без отката в демо | | mmap поверхности недоступен | `read()`-снимки (задокументированный fallback) | | кадр короче `stride*height` | `ShortRead` — ошибка, а не наполовину нарисованный кадр | -Реконнект — **повторный запуск окна**, а не кнопка в нём: сессию спавнит ядро -на первом `open`, а «предложить reconnect» в пиксельном зеркале пришлось бы -делать отдельным UI ввода, которого в v1 нет. Пауза перед закрытием нужна, -чтобы сообщение успели прочитать, а не чтобы спрятать конец сессии. +Реконнект — **в том же окне**: сессию спавнит ядро на первом `open`, поэтому +клиент после `ENODEV` не закрывает окно и не делает второй `create`, а ждёт +Enter и переоткрывает устройства (`FrameSource::respawn` + `InputSink::respawn`). +Второго окна не появляется, `duplicate window` при respawn невозможен, а +композитор не видит ни нового клиента, ни нового окна. Закрыть окно насовсем — +кнопкой композитора; тогда при следующем запуске приложения окно создаётся +заново (это уже штатный путь `create`, а не respawn). ### Диагностика live-прогона @@ -557,7 +560,8 @@ shell). * поверхность не несёт DEC-режимов → стрелки всегда normal, bracketed paste и mouse-reporting из окна не включаются; * одна сессия на окно; второй клиент увидит ту же поверхность (и получит - `duplicate window`/`not owner`, если возьмёт занятый `--window-id`); + `duplicate window`/`not owner`, если возьмёт занятый `--window-id`, — поэтому + respawn после `exit` идёт в том же окне, а не вторым подключением); * **ввод окна требует, чтобы консоль не имела foreground-совместимого процесса.** `vtinput::write_session` при `FG_PID != 0` отдаёт байты в stdin этого процесса: окно, запущенное прямо из kernel-shell как foreground-задача diff --git a/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs b/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs index cd0b9127..efa2f3d0 100644 --- a/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs +++ b/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs @@ -34,8 +34,8 @@ use pagh_terminal::client::{close_name, error_name, Event, ShmFrame, SurfaceClie use pagh_terminal::demo::{self, DemoShell}; use pagh_terminal::font::{CELL_H, CELL_W}; use pagh_terminal::kernelsession::{ - is_missing_device, is_session_end, render_notice, Draw, FileInput, KernelFrame, KeyForwarder, - VtFbError, + is_missing_device, is_session_end, render_notice, Draw, FileInput, FrameSource, KernelFrame, + KeyForwarder, VtFbError, }; use pagh_terminal::keys::{self, KeyModes}; use pagh_terminal::protocol::{buttons, InputEvent}; @@ -1450,6 +1450,10 @@ fn run_kernel_session(args: &Args, socket: &str) -> Result<(), String> { let mut dirty = true; let mut last_commit = Instant::now(); let mut input_error_reported = false; + // Сессия завершилась (`exit` -> ENODEV): окно осталось, ждём Enter, чтобы + // переоткрыть устройство и поднять новую сессию в ЭТОМ же окне. + let mut awaiting_respawn = false; + let mut notice_pending = false; // `--vt-trace` (или переменная окружения) печатает каждый отрисованный // кадр: в гостевой консоли это serial-доказательство того, что generation // растёт с выводом сессии, а не «кадр застыл». @@ -1458,7 +1462,15 @@ fn run_kernel_session(args: &Args, socket: &str) -> Result<(), String> { loop { // 1. Кадр сессии: перерисовываем окно только когда ядро опубликовало // новый generation — иначе простой не жжёт CPU на блит. - { + if awaiting_respawn && notice_pending { + let canvas = canvas_mut(&mut shm, &mut fallback); + render_notice(canvas, &theme, ENDED_NOTICE); + notice_pending = false; + dirty = true; + } + if awaiting_respawn { + // Кадр не блитится: поверхность принадлежала завершившейся сессии. + } else { let canvas = canvas_mut(&mut shm, &mut fallback); match frame.draw_if_changed(canvas, &theme) { Ok(Draw::Drawn { generation }) => { @@ -1469,14 +1481,13 @@ fn run_kernel_session(args: &Args, socket: &str) -> Result<(), String> { } Ok(Draw::Unchanged) => {} Err(VtFbError::Ended) => { - return end_kernel_session( - &mut client, - &mut shm, - &mut diag, - &theme, - width, - height, - ENDED_NOTICE, + // Честная плашка и ожидание Enter: сессия ядра закончилась, + // но окно — нет. Это и есть respawn без второго окна. + awaiting_respawn = true; + notice_pending = true; + diag.line( + "kernel session ended (the shell exited); window kept, \ + press Enter to restart the session", ); } Err(error) => { @@ -1593,6 +1604,45 @@ fn run_kernel_session(args: &Args, socket: &str) -> Result<(), String> { } } Event::ShmReady { .. } => {} + Event::Input(InputEvent::Key { + code, + pressed, + modifiers, + }) if awaiting_respawn => { + // Любая клавиша (в первую очередь Enter) — просьба поднять + // новую сессию: переоткрываем vtinput1 и vtfb1. Старые fd + // принадлежали завершившейся сессии, поэтому open спавнит + // новую, а окно остаётся тем же. + let _ = code; + let _ = modifiers; + if pressed { + match respawn_kernel_session(&mut frame, &mut forwarder, &mut diag) { + Ok(()) => { + awaiting_respawn = false; + notice_pending = false; + dirty = true; + } + Err(error) => { + let message = error.message(); + diag.line(&format!("cannot restart the session: {message}")); + let _ = end_kernel_session( + &mut client, + &mut shm, + &mut diag, + &theme, + width, + height, + &[ + "[kernel session] the session ended and could not be restarted", + "", + message.as_str(), + ], + ); + return Err(message); + } + } + } + } Event::Input(InputEvent::Key { code, pressed, @@ -1641,13 +1691,36 @@ fn run_kernel_session(args: &Args, socket: &str) -> Result<(), String> { } /// Что показать в окне, когда `exit` в сессии ядра завершил её (`ENODEV`). +/// +/// Окно при этом НЕ закрывается: Enter переоткрывает устройство, ядро поднимает +/// новую сессию, и она продолжается в том же окне. Именно поэтому respawn не +/// создаёт второе окно и не упирается в `duplicate window`. const ENDED_NOTICE: &[&str] = &[ "[kernel session] the shell session has ended.", "", - "The kernel starts a fresh session on the next open, so relaunch", - "pagh-terminal to reconnect. Nothing is simulated in the meantime.", + "Press Enter to start a new session in this window.", + "The window itself stays: no second window is created.", ]; +/// Поднять новую сессию ядра в том же окне: переоткрыть ввод и поверхность. +/// +/// Ядро спавнит сессию на первом `open` любого из двух устройств; клиент не +/// создаёт второй `create`, поэтому композитор не может ответить +/// `duplicate window`. +fn respawn_kernel_session( + frame: &mut KernelFrame>, + forwarder: &mut KeyForwarder, + diag: &mut Diag, +) -> Result<(), VtFbError> { + forwarder.respawn().map_err(VtFbError::Io)?; + let info = frame.respawn()?; + diag.line(&format!( + "kernel session restarted in the same window ({}x{}, stride {}, generation {})", + info.width, info.height, info.stride, info.generation + )); + Ok(()) +} + /// Получить текущий холст окна (общий mmap или локальный fallback). fn canvas_mut<'a>( shm: &'a mut Option, diff --git a/rust-apps/pagh-terminal/src/bin/pagh-terminal/devfs.rs b/rust-apps/pagh-terminal/src/bin/pagh-terminal/devfs.rs index f7d7b201..cd74c067 100644 --- a/rust-apps/pagh-terminal/src/bin/pagh-terminal/devfs.rs +++ b/rust-apps/pagh-terminal/src/bin/pagh-terminal/devfs.rs @@ -95,6 +95,8 @@ struct MmapSurface { /// Держим fd открытым: закрытие `fd` при живом отображении — законно, но /// повторный ioctl `generation` делается по этому же fd. file: File, + /// Путь нужен для `respawn`: после `ENODEV` сессию поднимает новый `open`. + path: String, base: *mut u8, len: usize, info: VtFbInfo, @@ -139,6 +141,7 @@ impl MmapSurface { Ok(( MmapSurface { file, + path: path.to_string(), base: base as *mut u8, len, info, @@ -162,6 +165,47 @@ impl FrameSource for MmapSurface { Ok(info) } + fn respawn(&mut self) -> Result<(), VtFbError> { + // Ядро поднимает новую сессию на первом `open` устройства, а прежний fd + // относится к завершившейся. Порядок: сначала новый open + mmap (если он + // не удался, старое отображение не тронуто), затем снять старое и + // подменить поля — окно клиента при этом не меняется, второго `create` + // композитор не увидит. + let file = File::open(&self.path)?; + let info = query_info(&file)?; + let len = info.pixels_len(); + if len == 0 { + return Err(VtFbError::BadInfo( + "the kernel reported a zero-byte framebuffer", + )); + } + // SAFETY: PROT_READ+MAP_SHARED на fd, который живёт в `file`; + // MAP_FAILED проверяется до любого чтения (как в `new`). + let base = unsafe { + mmap( + std::ptr::null_mut(), + len, + PROT_READ, + MAP_SHARED, + file.as_raw_fd(), + 0, + ) + }; + if base as isize == -1 { + return Err(VtFbError::Io(io::Error::last_os_error())); + } + // SAFETY: старое отображение создано в `new`/`respawn` и до сих пор не + // снималось. + unsafe { + munmap(self.base as *mut c_void, self.len); + } + self.file = file; // старый fd закрывается здесь + self.base = base as *mut u8; + self.len = len; + self.info = info; + Ok(()) + } + fn with_pixels(&mut self, f: &mut dyn FnMut(&[u8])) -> Result<(), VtFbError> { let len = self.info.pixels_len().min(self.len); // SAFETY: `base..base+len` — отображение, созданное в `new` и живое до diff --git a/rust-apps/pagh-terminal/src/kernelsession.rs b/rust-apps/pagh-terminal/src/kernelsession.rs index 7bb7f844..d64913ae 100644 --- a/rust-apps/pagh-terminal/src/kernelsession.rs +++ b/rust-apps/pagh-terminal/src/kernelsession.rs @@ -182,8 +182,8 @@ impl VtFbError { match self { VtFbError::Io(error) => format!("device I/O error: {error}"), VtFbError::Ended => { - "the kernel shell session ended (ENODEV). The kernel starts a new one on the \ - next open — relaunch the window to reconnect." + "the kernel shell session ended (ENODEV). The next open starts a new one — \ + press Enter in the window to restart the session there." .to_string() } VtFbError::BadInfo(what) => format!("kernel framebuffer contract violation: {what}"), @@ -227,11 +227,24 @@ pub trait FrameSource { /// буфера, а у read-fallback он есть, и оба обязаны выглядеть одинаково для /// безопасного кода lib-крейта (`#![forbid(unsafe_code)]`). fn with_pixels(&mut self, f: &mut dyn FnMut(&[u8])) -> Result<(), VtFbError>; + + /// Переоткрыть поверхность после `ENODEV` — ядро спавнит новую сессию на + /// первом `open`. Устройство переоткрывается, а окно клиента остаётся тем + /// же: перезапуск сессии не должен требовать нового окна (иначе композитор + /// получает `duplicate window` на тот же id). + fn respawn(&mut self) -> Result<(), VtFbError> { + Err(VtFbError::Ended) + } } /// Приёмник VT-байтов ввода (в бою — `/dev/vtinput1`). pub trait InputSink { fn send(&mut self, bytes: &[u8]) -> io::Result<()>; + + /// Переоткрыть устройство после `ENODEV` (новая сессия ядра). + fn respawn(&mut self) -> io::Result<()> { + Ok(()) + } } impl FrameSource for Box { @@ -285,6 +298,17 @@ impl FrameSource for ReadFrameSource { Ok(self.info) } + fn respawn(&mut self) -> Result<(), VtFbError> { + // Свежий open — это и есть respawn: ядро поднимает сессию на первом + // open устройства, а старый fd остался от завершившейся сессии. + let file = File::open(&self.path)?; + let mut header = [0u8; INFO_LEN]; + read_exact_at(&file, &mut header, 0)?; + self.file = file; + self.info = VtFbInfo::parse(&header)?; + Ok(()) + } + fn with_pixels(&mut self, f: &mut dyn FnMut(&[u8])) -> Result<(), VtFbError> { // Один связный снимок: заголовок и пиксели читаются из offset 0 в // одном проходе, поэтому geometry/generation принадлежат тем же @@ -307,12 +331,14 @@ impl FrameSource for ReadFrameSource { /// `InputSink` поверх обычного файла (`/dev/vtinput1`). pub struct FileInput { file: File, + path: PathBuf, } impl FileInput { pub fn open(path: impl AsRef) -> io::Result { - let file = OpenOptions::new().write(true).open(path)?; - Ok(FileInput { file }) + let path = path.as_ref().to_path_buf(); + let file = OpenOptions::new().write(true).open(&path)?; + Ok(FileInput { file, path }) } } @@ -321,6 +347,11 @@ impl InputSink for FileInput { // Без flush: это символьное устройство, `write` уже отдал байты ядру. self.file.write_all(bytes) } + + fn respawn(&mut self) -> io::Result<()> { + self.file = OpenOptions::new().write(true).open(&self.path)?; + Ok(()) + } } /// Раскладка кадра сессии внутри окна: `dst`-прямоугольник и его смещение. @@ -458,6 +489,18 @@ impl KernelFrame { self.full = true; } + /// Поднять новую сессию ядра на месте той, что завершилась (`ENODEV`). + /// + /// Окно клиента не пересоздаётся: переоткрывается только устройство, поэтому + /// композитор не видит второго `create` и `duplicate window` невозможен. + pub fn respawn(&mut self) -> Result { + self.source.respawn()?; + self.last_generation = None; + self.full = true; + self.info = self.source.poll()?; + Ok(self.info) + } + /// Перерисовать окно, если ядро опубликовало новый кадр. pub fn draw_if_changed( &mut self, @@ -545,6 +588,11 @@ impl KeyForwarder { pub fn sink(&self) -> &S { &self.sink } + + /// Переоткрыть устройство ввода для новой сессии. + pub fn respawn(&mut self) -> io::Result<()> { + self.sink.respawn() + } } /// Нарисовать честное сообщение (ошибка устройства, конец сессии) в окне. diff --git a/rust-apps/pagh-terminal/tests/kernel_session.rs b/rust-apps/pagh-terminal/tests/kernel_session.rs index 3cddea6b..9bc86aac 100644 --- a/rust-apps/pagh-terminal/tests/kernel_session.rs +++ b/rust-apps/pagh-terminal/tests/kernel_session.rs @@ -62,6 +62,8 @@ struct MockFb { failure: Option<&'static str>, /// Сколько `poll()`-ов отдать кадр до отказа (0 — отказ сразу). fail_after: usize, + /// Сколько раз источник переоткрывали (`ENODEV` -> respawn). + respawned: usize, } impl MockFb { @@ -72,6 +74,7 @@ impl MockFb { polls: 0, failure: None, fail_after: 0, + respawned: 0, } } @@ -95,6 +98,17 @@ impl FrameSource for MockFb { } } + fn respawn(&mut self) -> Result<(), VtFbError> { + // Ядро поднимает новую сессию на первом open: свежий счётчик generation. + self.respawned += 1; + self.polls = 0; + self.failure = None; + self.fail_after = 0; + self.info.generation = 1; + self.pixels = solid_pixels(&self.info, (0, 0, 0)); + Ok(()) + } + fn with_pixels(&mut self, f: &mut dyn FnMut(&[u8])) -> Result<(), VtFbError> { if self.failure == Some("short") { let short = self.pixels.len() / 2; @@ -109,6 +123,7 @@ impl FrameSource for MockFb { /// Куда «устройство ввода» складывает байты в тестах. struct MockInput { written: Vec, + respawns: usize, } impl InputSink for MockInput { @@ -116,6 +131,11 @@ impl InputSink for MockInput { self.written.extend_from_slice(bytes); Ok(()) } + + fn respawn(&mut self) -> io::Result<()> { + self.respawns += 1; + Ok(()) + } } #[test] @@ -237,8 +257,8 @@ fn session_end_is_reported_honestly_and_not_masked() { match frame.draw_if_changed(&mut canvas, &theme) { Err(error) if error.is_ended() => { assert!( - error.message().contains("relaunch"), - "сообщение обязано говорить, как переподключиться: {}", + error.message().contains("press Enter"), + "сообщение обязано говорить, как переподключиться в этом окне: {}", error.message() ); } @@ -334,6 +354,7 @@ fn read_fallback_tracks_generation_on_a_plain_file() { fn keys_become_vt_bytes_for_the_kernel_input() { let mut forwarder = KeyForwarder::new(MockInput { written: Vec::new(), + respawns: 0, }); use pagh_terminal::keys::evdev; // PDP/1 modifier bits (same wire values as `protocol::mods`). @@ -543,6 +564,47 @@ fn missing_kernel_devices_fall_back_to_the_pipe_shell_session() { let _ = std::fs::remove_dir_all(&dir); } +/// Завершившаяся сессия поднимается заново в ТОМ ЖЕ кадре/окне: клиент +/// переоткрывает устройство, а не создаёт второе окно (`duplicate window`). +#[test] +fn a_finished_session_restarts_in_the_same_frame() { + let mut fb = MockFb::new(info(2, 2, 10), (0, 0, 0)); + fb.failure = Some("ended"); + // open() = poll #1, первый кадр = #2, отказ — на следующем. + fb.fail_after = 2; + let mut frame = KernelFrame::open(fb).expect("open"); + let theme = Theme::default(); + let mut canvas = Canvas::new(2, 2, theme.bg); + assert!(frame.draw_if_changed(&mut canvas, &theme).is_ok()); + match frame.draw_if_changed(&mut canvas, &theme) { + Err(error) if error.is_ended() => {} + other => panic!("expected Ended, got {other:?}"), + } + + let info = frame.respawn().expect("respawn in the same window"); + assert_eq!(info.generation, 1, "новая сессия начинает счёт заново"); + assert_eq!( + frame.draw_if_changed(&mut canvas, &theme).unwrap(), + Draw::Drawn { generation: 1 }, + "после respawn кадр рисуется в том же холсте" + ); +} + +/// Переоткрытие ввода после `ENODEV`: пишем уже в новую сессию. +#[test] +fn input_device_is_reopened_for_the_new_session() { + let mut forwarder = KeyForwarder::new(MockInput { + written: Vec::new(), + respawns: 0, + }); + use pagh_terminal::keys::evdev; + forwarder.handle_key(evdev::KEY_H, true, 0).expect("write"); + forwarder.respawn().expect("reopen input"); + assert_eq!(forwarder.sink().respawns, 1); + forwarder.handle_key(evdev::KEY_A, true, 0).expect("write"); + assert_eq!(forwarder.sink().written, b"ha"); +} + /// Диагностика режима должна уметь уходить в файл: desktop запускает клиента /// `--launch-target` в фоновой группе консоли, где TOSTOP останавливает первую /// же запись в stderr (SIGTTOU). `--log-file` — штатный путь для такого запуска. From f9ced4f2e0da012ef303b4178eed8bb7a1601399 Mon Sep 17 00:00:00 2001 From: pagh-agent Date: Sat, 21 Nov 2026 18:54:24 +0300 Subject: [PATCH 08/12] terminal: close the old session devices before reopening them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The in-window respawn opened the new devices first and only then dropped the old fds. The kernel resets its open-fd counter when a session exits (its fds outlive the session on purpose, frames stay pinned), so the late `close` of the OLD fd after `note_open` of the NEW session drove the counter back to zero, the kernel asked the freshly spawned session to exit, and the surface's ioctl answered ENODEV — the window restarted and died in the same breath. Respawn now closes both old handles first (`FileInput` and `MmapSurface` hold `Option`), and only then opens the input device and the surface. With the counter already at zero the stale `close` is a no-op, and the new session stays alive. Test suite unchanged and green (174); the live evidence for the Enter-respawn path is rerun after this commit. --- .../src/bin/pagh-terminal/devfs.rs | 40 ++++++++++++------- rust-apps/pagh-terminal/src/kernelsession.rs | 19 +++++++-- 2 files changed, 40 insertions(+), 19 deletions(-) diff --git a/rust-apps/pagh-terminal/src/bin/pagh-terminal/devfs.rs b/rust-apps/pagh-terminal/src/bin/pagh-terminal/devfs.rs index cd74c067..d85bc0c3 100644 --- a/rust-apps/pagh-terminal/src/bin/pagh-terminal/devfs.rs +++ b/rust-apps/pagh-terminal/src/bin/pagh-terminal/devfs.rs @@ -94,7 +94,8 @@ pub fn open_frame_source(path: &str) -> Result { struct MmapSurface { /// Держим fd открытым: закрытие `fd` при живом отображении — законно, но /// повторный ioctl `generation` делается по этому же fd. - file: File, + /// `None` — fd закрыт (между `ENODEV` и respawn). + file: Option, /// Путь нужен для `respawn`: после `ENODEV` сессию поднимает новый `open`. path: String, base: *mut u8, @@ -140,7 +141,7 @@ impl MmapSurface { ); Ok(( MmapSurface { - file, + file: Some(file), path: path.to_string(), base: base as *mut u8, len, @@ -153,7 +154,10 @@ impl MmapSurface { impl FrameSource for MmapSurface { fn poll(&mut self) -> Result { - let info = query_info(&self.file)?; + let Some(file) = self.file.as_ref() else { + return Err(VtFbError::Ended); + }; + let info = query_info(file)?; if info.pixels_len() > self.len { // Разрешение kernel-VT сменилось на живой сессии — это контрактный // разрыв, а не повод читать за отображением. @@ -166,11 +170,19 @@ impl FrameSource for MmapSurface { } fn respawn(&mut self) -> Result<(), VtFbError> { - // Ядро поднимает новую сессию на первом `open` устройства, а прежний fd - // относится к завершившейся. Порядок: сначала новый open + mmap (если он - // не удался, старое отображение не тронуто), затем снять старое и - // подменить поля — окно клиента при этом не меняется, второго `create` - // композитор не увидит. + // Порядок несущий: СНАЧАЛА снять отображение и закрыть старый fd, только + // потом `open`. Ядро спавнит новую сессию на первом open, а `close` + // старого fd после этого уменьшил бы счётчик открытых устройств до нуля — + // ядро попросило бы новую сессию выйти, и следующий ioctl вернул бы + // ENODEV (окно «перезапустилось и сразу умерло»). + // SAFETY: отображение создано в `new`/`respawn` и ещё не снималось. + unsafe { + munmap(self.base as *mut c_void, self.len); + } + self.base = std::ptr::null_mut(); + self.len = 0; + self.file = None; // старый fd закрывается здесь + let file = File::open(&self.path)?; let info = query_info(&file)?; let len = info.pixels_len(); @@ -194,12 +206,7 @@ impl FrameSource for MmapSurface { if base as isize == -1 { return Err(VtFbError::Io(io::Error::last_os_error())); } - // SAFETY: старое отображение создано в `new`/`respawn` и до сих пор не - // снималось. - unsafe { - munmap(self.base as *mut c_void, self.len); - } - self.file = file; // старый fd закрывается здесь + self.file = Some(file); self.base = base as *mut u8; self.len = len; self.info = info; @@ -218,7 +225,10 @@ impl FrameSource for MmapSurface { impl Drop for MmapSurface { fn drop(&mut self) { - // SAFETY: отображение создано `mmap` в `new` и ещё не снималось. + if self.base.is_null() || self.len == 0 { + return; + } + // SAFETY: отображение создано `mmap` в `new`/`respawn` и ещё не снималось. unsafe { munmap(self.base as *mut c_void, self.len); } diff --git a/rust-apps/pagh-terminal/src/kernelsession.rs b/rust-apps/pagh-terminal/src/kernelsession.rs index d64913ae..c1116d7e 100644 --- a/rust-apps/pagh-terminal/src/kernelsession.rs +++ b/rust-apps/pagh-terminal/src/kernelsession.rs @@ -330,7 +330,8 @@ impl FrameSource for ReadFrameSource { /// `InputSink` поверх обычного файла (`/dev/vtinput1`). pub struct FileInput { - file: File, + /// `None` — устройство закрыто (например, между `ENODEV` и respawn). + file: Option, path: PathBuf, } @@ -338,18 +339,28 @@ impl FileInput { pub fn open(path: impl AsRef) -> io::Result { let path = path.as_ref().to_path_buf(); let file = OpenOptions::new().write(true).open(&path)?; - Ok(FileInput { file, path }) + Ok(FileInput { + file: Some(file), + path, + }) } } impl InputSink for FileInput { fn send(&mut self, bytes: &[u8]) -> io::Result<()> { // Без flush: это символьное устройство, `write` уже отдал байты ядру. - self.file.write_all(bytes) + match self.file.as_mut() { + Some(file) => file.write_all(bytes), + None => Err(io::Error::from_raw_os_error(ENODEV)), + } } fn respawn(&mut self) -> io::Result<()> { - self.file = OpenOptions::new().write(true).open(&self.path)?; + // Закрыть старый fd ДО нового `open`: его `close` иначе придёт после + // `note_open` новой сессии, счётчик открытых fd дойдёт до нуля и ядро + // попросит только что поднятую сессию выйти (окно получит ENODEV). + self.file = None; + self.file = Some(OpenOptions::new().write(true).open(&self.path)?); Ok(()) } } From 9925315a356fa4f0348ee2ebf33f88e8cb3cc324 Mon Sep 17 00:00:00 2001 From: pagh-agent Date: Sat, 21 Nov 2026 19:02:06 +0300 Subject: [PATCH 09/12] terminal: close every old device before reopening any Closing the old surface fd after the input device had already been reopened still drove the kernel's per-session open counter to zero: the counter is reset when the session exits, so one late `close` is enough to make the kernel ask the just-spawned session to exit, and the next ioctl answers ENODEV. The window restarted and died immediately. Respawn is now two phases over both devices: `close` on the input sink and on the frame source, then `respawn` on the input and on the surface. `FileInput` and `MmapSurface` hold `Option`, so a closed handle is explicit and its late `close` cannot land after the spawn. The pure predicate lives in the trait's docs rather than in a comment beside one call site. Tests cover the hooks (close is called once, reopen follows, sinks keep the close-then-open order); 174 host tests green. --- .../pagh-terminal/src/bin/pagh-terminal.rs | 5 +++ .../src/bin/pagh-terminal/devfs.rs | 25 ++++++----- rust-apps/pagh-terminal/src/kernelsession.rs | 42 +++++++++++++++++-- .../pagh-terminal/tests/kernel_session.rs | 19 +++++++++ 4 files changed, 77 insertions(+), 14 deletions(-) diff --git a/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs b/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs index efa2f3d0..5971de56 100644 --- a/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs +++ b/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs @@ -1712,6 +1712,11 @@ fn respawn_kernel_session( forwarder: &mut KeyForwarder, diag: &mut Diag, ) -> Result<(), VtFbError> { + // Сначала закрыть ОБА старых устройства, и только потом открывать новые: + // ядро сбрасывает счётчик открытых fd при выходе сессии, поэтому «поздний» + // close после `open` новой сессии попросил бы её выйти (ENODEV на ioctl). + forwarder.close().map_err(VtFbError::Io)?; + frame.close_source()?; forwarder.respawn().map_err(VtFbError::Io)?; let info = frame.respawn()?; diag.line(&format!( diff --git a/rust-apps/pagh-terminal/src/bin/pagh-terminal/devfs.rs b/rust-apps/pagh-terminal/src/bin/pagh-terminal/devfs.rs index d85bc0c3..d38e016b 100644 --- a/rust-apps/pagh-terminal/src/bin/pagh-terminal/devfs.rs +++ b/rust-apps/pagh-terminal/src/bin/pagh-terminal/devfs.rs @@ -169,20 +169,25 @@ impl FrameSource for MmapSurface { Ok(info) } - fn respawn(&mut self) -> Result<(), VtFbError> { - // Порядок несущий: СНАЧАЛА снять отображение и закрыть старый fd, только - // потом `open`. Ядро спавнит новую сессию на первом open, а `close` - // старого fd после этого уменьшил бы счётчик открытых устройств до нуля — - // ядро попросило бы новую сессию выйти, и следующий ioctl вернул бы - // ENODEV (окно «перезапустилось и сразу умерло»). - // SAFETY: отображение создано в `new`/`respawn` и ещё не снималось. - unsafe { - munmap(self.base as *mut c_void, self.len); + fn close(&mut self) -> Result<(), VtFbError> { + // Снять отображение и закрыть fd. Вызывается ДО любого нового `open`: + // `close` пережившего сессию fd после `open` новой уменьшил бы счётчик + // открытых устройств до нуля, и ядро попросило бы новую сессию выйти. + if !self.base.is_null() && self.len > 0 { + // SAFETY: отображение создано в `new`/`respawn` и ещё не снималось. + unsafe { + munmap(self.base as *mut c_void, self.len); + } } self.base = std::ptr::null_mut(); self.len = 0; - self.file = None; // старый fd закрывается здесь + self.file = None; + Ok(()) + } + fn respawn(&mut self) -> Result<(), VtFbError> { + // `close` уже закрыл старый fd (общий порядок — см. `FrameSource::close`), + // поэтому здесь только новый open + mmap: open и спавнит сессию. let file = File::open(&self.path)?; let info = query_info(&file)?; let len = info.pixels_len(); diff --git a/rust-apps/pagh-terminal/src/kernelsession.rs b/rust-apps/pagh-terminal/src/kernelsession.rs index c1116d7e..887d7d0e 100644 --- a/rust-apps/pagh-terminal/src/kernelsession.rs +++ b/rust-apps/pagh-terminal/src/kernelsession.rs @@ -228,6 +228,21 @@ pub trait FrameSource { /// безопасного кода lib-крейта (`#![forbid(unsafe_code)]`). fn with_pixels(&mut self, f: &mut dyn FnMut(&[u8])) -> Result<(), VtFbError>; + /// Переоткрыть поверхность после `ENODEV` — ядро спавнит новую сессию на + /// первом `open`. Устройство переоткрывается, а окно клиента остаётся тем + /// же: перезапуск сессии не должен требовать нового окна (иначе композитор + /// получает `duplicate window` на тот же id). + /// Закрыть устройство перед respawn — **вместе** со всеми остальными. + /// + /// Несущий порядок: ядро сбрасывает счётчик открытых fd сессии при её + /// выходе, а `close` переживших сессию fd считает заново. Если закрыть один + /// старый fd уже после `open` нового, счётчик дойдёт до нуля и ядро + /// попросит только что поднятую сессию выйти. Поэтому клиент сначала + /// закрывает ВСЕ старые устройства, и только потом открывает новые. + fn close(&mut self) -> Result<(), VtFbError> { + Ok(()) + } + /// Переоткрыть поверхность после `ENODEV` — ядро спавнит новую сессию на /// первом `open`. Устройство переоткрывается, а окно клиента остаётся тем /// же: перезапуск сессии не должен требовать нового окна (иначе композитор @@ -241,6 +256,11 @@ pub trait FrameSource { pub trait InputSink { fn send(&mut self, bytes: &[u8]) -> io::Result<()>; + /// Закрыть устройство (перед общим close-then-open respawn). + fn close(&mut self) -> io::Result<()> { + Ok(()) + } + /// Переоткрыть устройство после `ENODEV` (новая сессия ядра). fn respawn(&mut self) -> io::Result<()> { Ok(()) @@ -355,11 +375,15 @@ impl InputSink for FileInput { } } - fn respawn(&mut self) -> io::Result<()> { - // Закрыть старый fd ДО нового `open`: его `close` иначе придёт после - // `note_open` новой сессии, счётчик открытых fd дойдёт до нуля и ядро - // попросит только что поднятую сессию выйти (окно получит ENODEV). + fn close(&mut self) -> io::Result<()> { self.file = None; + Ok(()) + } + + fn respawn(&mut self) -> io::Result<()> { + // К этому моменту `close` уже закрыл старый fd (ядро сбрасывает счётчик + // при выходе сессии), поэтому новый `open` — единственный: он и спавнит + // сессию, и не даёт «позднему» close счётчику упасть до нуля. self.file = Some(OpenOptions::new().write(true).open(&self.path)?); Ok(()) } @@ -500,6 +524,11 @@ impl KernelFrame { self.full = true; } + /// Закрыть поверхность (перед общим close-then-open respawn). + pub fn close_source(&mut self) -> Result<(), VtFbError> { + self.source.close() + } + /// Поднять новую сессию ядра на месте той, что завершилась (`ENODEV`). /// /// Окно клиента не пересоздаётся: переоткрывается только устройство, поэтому @@ -600,6 +629,11 @@ impl KeyForwarder { &self.sink } + /// Закрыть устройство ввода (перед общим close-then-open respawn). + pub fn close(&mut self) -> io::Result<()> { + self.sink.close() + } + /// Переоткрыть устройство ввода для новой сессии. pub fn respawn(&mut self) -> io::Result<()> { self.sink.respawn() diff --git a/rust-apps/pagh-terminal/tests/kernel_session.rs b/rust-apps/pagh-terminal/tests/kernel_session.rs index 9bc86aac..0f524d5f 100644 --- a/rust-apps/pagh-terminal/tests/kernel_session.rs +++ b/rust-apps/pagh-terminal/tests/kernel_session.rs @@ -64,6 +64,8 @@ struct MockFb { fail_after: usize, /// Сколько раз источник переоткрывали (`ENODEV` -> respawn). respawned: usize, + /// Сколько раз источник закрывали перед переоткрытием. + closed: usize, } impl MockFb { @@ -75,6 +77,7 @@ impl MockFb { failure: None, fail_after: 0, respawned: 0, + closed: 0, } } @@ -98,6 +101,11 @@ impl FrameSource for MockFb { } } + fn close(&mut self) -> Result<(), VtFbError> { + self.closed += 1; + Ok(()) + } + fn respawn(&mut self) -> Result<(), VtFbError> { // Ядро поднимает новую сессию на первом open: свежий счётчик generation. self.respawned += 1; @@ -124,6 +132,7 @@ impl FrameSource for MockFb { struct MockInput { written: Vec, respawns: usize, + closes: usize, } impl InputSink for MockInput { @@ -132,6 +141,11 @@ impl InputSink for MockInput { Ok(()) } + fn close(&mut self) -> io::Result<()> { + self.closes += 1; + Ok(()) + } + fn respawn(&mut self) -> io::Result<()> { self.respawns += 1; Ok(()) @@ -355,6 +369,7 @@ fn keys_become_vt_bytes_for_the_kernel_input() { let mut forwarder = KeyForwarder::new(MockInput { written: Vec::new(), respawns: 0, + closes: 0, }); use pagh_terminal::keys::evdev; // PDP/1 modifier bits (same wire values as `protocol::mods`). @@ -581,6 +596,7 @@ fn a_finished_session_restarts_in_the_same_frame() { other => panic!("expected Ended, got {other:?}"), } + frame.close_source().expect("close the surface first"); let info = frame.respawn().expect("respawn in the same window"); assert_eq!(info.generation, 1, "новая сессия начинает счёт заново"); assert_eq!( @@ -596,10 +612,13 @@ fn input_device_is_reopened_for_the_new_session() { let mut forwarder = KeyForwarder::new(MockInput { written: Vec::new(), respawns: 0, + closes: 0, }); use pagh_terminal::keys::evdev; forwarder.handle_key(evdev::KEY_H, true, 0).expect("write"); + forwarder.close().expect("close the old device"); forwarder.respawn().expect("reopen input"); + assert_eq!(forwarder.sink().closes, 1); assert_eq!(forwarder.sink().respawns, 1); forwarder.handle_key(evdev::KEY_A, true, 0).expect("write"); assert_eq!(forwarder.sink().written, b"ha"); From a0be8ffec334bf0b029aeed569fc177873cd2632 Mon Sep 17 00:00:00 2001 From: pagh-agent Date: Sat, 21 Nov 2026 19:08:22 +0300 Subject: [PATCH 10/12] terminal: log and retry the respawn steps The Enter-respawn path had no visibility into which failed: the client logged only the final ENODEV. It now names the step (devices closed / input reopened / surface pending) and retries the surface ioctl while the error is ENODEV, which is the state a just-spawned session can be in for a moment. --- .../pagh-terminal/src/bin/pagh-terminal.rs | 31 +++++++++++++++---- 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs b/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs index 5971de56..08b7fd54 100644 --- a/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs +++ b/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs @@ -1717,13 +1717,32 @@ fn respawn_kernel_session( // close после `open` новой сессии попросил бы её выйти (ENODEV на ioctl). forwarder.close().map_err(VtFbError::Io)?; frame.close_source()?; + diag.line("restart: devices closed, reopening input"); forwarder.respawn().map_err(VtFbError::Io)?; - let info = frame.respawn()?; - diag.line(&format!( - "kernel session restarted in the same window ({}x{}, stride {}, generation {})", - info.width, info.height, info.stride, info.generation - )); - Ok(()) + diag.line("restart: input reopened, reopening the surface"); + // Новая сессия спавнится первым `open`; её задача может успеть выполниться + // на другом ядре/тике, поэтому сбой ioctl повторяем — но только пока это + // именно ENODEV (иначе это настоящая ошибка устройства). + let mut last = VtFbError::Ended; + for attempt in 0..3 { + match frame.respawn() { + Ok(info) => { + diag.line(&format!( + "kernel session restarted in the same window \ + ({}x{}, stride {}, generation {})", + info.width, info.height, info.stride, info.generation + )); + return Ok(()); + } + Err(error) if error.is_ended() && attempt < 2 => { + diag.line(&format!("restart: surface not up yet ({error}), retrying")); + std::thread::sleep(Duration::from_millis(100)); + last = error; + } + Err(error) => return Err(error), + } + } + Err(last) } /// Получить текущий холст окна (общий mmap или локальный fallback). From 69a174d078f0c9719a64559cb45c3b429c3094de Mon Sep 17 00:00:00 2001 From: pagh-agent Date: Sat, 21 Nov 2026 21:03:22 +0300 Subject: [PATCH 11/12] =?UTF-8?q?terminal:=20one=20restart=20UX=20?= =?UTF-8?q?=E2=80=94=20wait=5Ffor=5Frestart,=20no=20second=20state=20machi?= =?UTF-8?q?ne?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- rust-apps/pagh-terminal/TERMINAL.md | 10 +- .../pagh-terminal/src/bin/pagh-terminal.rs | 170 +++++++++++------- 2 files changed, 113 insertions(+), 67 deletions(-) diff --git a/rust-apps/pagh-terminal/TERMINAL.md b/rust-apps/pagh-terminal/TERMINAL.md index 190419a0..5358aa73 100644 --- a/rust-apps/pagh-terminal/TERMINAL.md +++ b/rust-apps/pagh-terminal/TERMINAL.md @@ -493,15 +493,19 @@ application cursor, bracketed paste, mouse) из неё не наблюдаем | ситуация | поведение | |---|---| -| `exit` в сессии → `ENODEV` | плашка «the shell session has ended / Press Enter to start a new session in this window»; окно **остаётся**, Enter переоткрывает `vtfb1`/`vtinput1` и ядро поднимает новую сессию в том же окне | +| `exit` в сессии → `ENODEV` | плашка «the shell session has ended / Press Enter to start a new session in this window, or Esc to close it»; окно **остаётся**, Enter/Space переоткрывает `vtfb1`/`vtinput1` и ядро поднимает новую сессию в том же окне, Esc закрывает окно | | `/dev/vtfb1` или `/dev/vtinput1` нет (`ENOENT`, старое ядро) | честная строка в stderr + откат на pipe-сессию (`--pipe-shell`-путь) | | устройство есть, но ioctl/mmap/read/write не работают | честное сообщение **в окне** + код возврата 2, без отката в демо | | mmap поверхности недоступен | `read()`-снимки (задокументированный fallback) | | кадр короче `stride*height` | `ShortRead` — ошибка, а не наполовину нарисованный кадр | Реконнект — **в том же окне**: сессию спавнит ядро на первом `open`, поэтому -клиент после `ENODEV` не закрывает окно и не делает второй `create`, а ждёт -Enter и переоткрывает устройства (`FrameSource::respawn` + `InputSink::respawn`). +клиент после `ENODEV` не закрывает окно и не делает второй `create`, а плашкой +ждёт Enter/Space и переоткрывает устройства (`wait_for_restart` → +`FrameSource::respawn` + `InputSink::respawn`). Это единственный restart-UX +клиента: тот же `wait_for_restart`/`draw_notice_frame` расширяет и #167, поэтому +семантика при объединении веток не меняется (Enter/Space — новая сессия в этом +окне, Esc — окно закрывается). Второго окна не появляется, `duplicate window` при respawn невозможен, а композитор не видит ни нового клиента, ни нового окна. Закрыть окно насовсем — кнопкой композитора; тогда при следующем запуске приложения окно создаётся diff --git a/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs b/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs index 08b7fd54..23c5190e 100644 --- a/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs +++ b/rust-apps/pagh-terminal/src/bin/pagh-terminal.rs @@ -1450,10 +1450,6 @@ fn run_kernel_session(args: &Args, socket: &str) -> Result<(), String> { let mut dirty = true; let mut last_commit = Instant::now(); let mut input_error_reported = false; - // Сессия завершилась (`exit` -> ENODEV): окно осталось, ждём Enter, чтобы - // переоткрыть устройство и поднять новую сессию в ЭТОМ же окне. - let mut awaiting_respawn = false; - let mut notice_pending = false; // `--vt-trace` (или переменная окружения) печатает каждый отрисованный // кадр: в гостевой консоли это serial-доказательство того, что generation // растёт с выводом сессии, а не «кадр застыл». @@ -1462,15 +1458,7 @@ fn run_kernel_session(args: &Args, socket: &str) -> Result<(), String> { loop { // 1. Кадр сессии: перерисовываем окно только когда ядро опубликовало // новый generation — иначе простой не жжёт CPU на блит. - if awaiting_respawn && notice_pending { - let canvas = canvas_mut(&mut shm, &mut fallback); - render_notice(canvas, &theme, ENDED_NOTICE); - notice_pending = false; - dirty = true; - } - if awaiting_respawn { - // Кадр не блитится: поверхность принадлежала завершившейся сессии. - } else { + { let canvas = canvas_mut(&mut shm, &mut fallback); match frame.draw_if_changed(canvas, &theme) { Ok(Draw::Drawn { generation }) => { @@ -1481,14 +1469,52 @@ fn run_kernel_session(args: &Args, socket: &str) -> Result<(), String> { } Ok(Draw::Unchanged) => {} Err(VtFbError::Ended) => { - // Честная плашка и ожидание Enter: сессия ядра закончилась, - // но окно — нет. Это и есть respawn без второго окна. - awaiting_respawn = true; - notice_pending = true; + // `exit` в сессии завершил её (`ENODEV`) — окно НЕ закрывается + // само: плашка, Enter/Space поднимает новую сессию в этом же + // окне, Esc закрывает. Это тот самый restart-UX, который #167 + // расширяет (та же семантика, тот же путь). diag.line( "kernel session ended (the shell exited); window kept, \ - press Enter to restart the session", + waiting for Enter to restart the session", ); + let restart = wait_for_restart(&mut client, &mut shm, &theme, width, height)?; + if !restart { + let _ = client.close(); + diag.line("kernel session ended; window closed"); + return Ok(()); + } + match respawn_kernel_session(&mut frame, &mut forwarder, &mut diag) { + Ok(()) => { + // `draw_notice_frame` отпустил ShmSurface: дальше + // полный кадр в локальный холст (как legacy-путь). + fallback = Some(Canvas::new(width as usize, height as usize, theme.bg)); + tracker.resize(pagh_ui::geom::Rect::new( + 0, + 0, + width as i32, + height as i32, + )); + dirty = true; + } + Err(error) => { + let message = error.message(); + diag.line(&format!("cannot restart the session: {message}")); + let _ = end_kernel_session( + &mut client, + &mut shm, + &mut diag, + &theme, + width, + height, + &[ + "[kernel session] the session ended and could not be restarted", + "", + message.as_str(), + ], + ); + return Err(message); + } + } } Err(error) => { let message = error.message(); @@ -1604,45 +1630,6 @@ fn run_kernel_session(args: &Args, socket: &str) -> Result<(), String> { } } Event::ShmReady { .. } => {} - Event::Input(InputEvent::Key { - code, - pressed, - modifiers, - }) if awaiting_respawn => { - // Любая клавиша (в первую очередь Enter) — просьба поднять - // новую сессию: переоткрываем vtinput1 и vtfb1. Старые fd - // принадлежали завершившейся сессии, поэтому open спавнит - // новую, а окно остаётся тем же. - let _ = code; - let _ = modifiers; - if pressed { - match respawn_kernel_session(&mut frame, &mut forwarder, &mut diag) { - Ok(()) => { - awaiting_respawn = false; - notice_pending = false; - dirty = true; - } - Err(error) => { - let message = error.message(); - diag.line(&format!("cannot restart the session: {message}")); - let _ = end_kernel_session( - &mut client, - &mut shm, - &mut diag, - &theme, - width, - height, - &[ - "[kernel session] the session ended and could not be restarted", - "", - message.as_str(), - ], - ); - return Err(message); - } - } - } - } Event::Input(InputEvent::Key { code, pressed, @@ -1690,18 +1677,73 @@ fn run_kernel_session(args: &Args, socket: &str) -> Result<(), String> { } } -/// Что показать в окне, когда `exit` в сессии ядра завершил её (`ENODEV`). -/// -/// Окно при этом НЕ закрывается: Enter переоткрывает устройство, ядро поднимает -/// новую сессию, и она продолжается в том же окне. Именно поэтому respawn не -/// создаёт второе окно и не упирается в `duplicate window`. +/// Плашка завершившейся сессии — общая для `wait_for_restart` (#167 расширяет +/// тот же путь, семантика не меняется). const ENDED_NOTICE: &[&str] = &[ "[kernel session] the shell session has ended.", "", - "Press Enter to start a new session in this window.", - "The window itself stays: no second window is created.", + "Press Enter to start a new session in this window,", + "or Esc to close it. Nothing is simulated in the meantime.", ]; +/// Нарисовать плашку клиента в окне и отдать её композитору. +/// +/// Имя и сигнатура совпадают с #167: там тот же кадр рисуется перед +/// `wait_for_restart`, и объединение веток не должно менять поведение. +fn draw_notice_frame( + client: &mut SurfaceClient, + shm: &mut Option, + theme: &Theme, + width: u32, + height: u32, + lines: &[&str], +) -> Result<(), String> { + if let Some(stale) = shm.take() { + let _ = client.release_shm(&stale); + } + let mut canvas = Canvas::new(width.max(64) as usize, height.max(32) as usize, theme.bg); + render_notice(&mut canvas, theme, lines); + commit_blocking(client, &canvas)?; + Ok(()) +} + +/// Показать плашку завершившейся сессии и дождаться решения. +/// +/// Семантика — общая с #167: Enter/Space → `Ok(true)` (поднять новую сессию в +/// ЭТОМ окне), Esc или закрытие окна сервером → `Ok(false)` (окно закрывается). +/// Сам перезапуск устройств делает вызывающий: в #147 это +/// [`respawn_kernel_session`], в #167 — его attach-код; путь один. +fn wait_for_restart( + client: &mut SurfaceClient, + shm: &mut Option, + theme: &Theme, + width: u32, + height: u32, +) -> Result { + draw_notice_frame(client, shm, theme, width, height, ENDED_NOTICE)?; + loop { + for event in client + .poll_events(Duration::ZERO) + .map_err(|e| format!("poll: {e}"))? + { + match event { + Event::Input(InputEvent::Key { + code, + pressed: true, + .. + }) => match code { + keys::evdev::KEY_ENTER | keys::evdev::KEY_SPACE => return Ok(true), + keys::evdev::KEY_ESC => return Ok(false), + _ => {} + }, + Event::Close { .. } => return Ok(false), + _ => {} + } + } + std::thread::sleep(Duration::from_millis(30)); + } +} + /// Поднять новую сессию ядра в том же окне: переоткрыть ввод и поверхность. /// /// Ядро спавнит сессию на первом `open` любого из двух устройств; клиент не From 4bff619f0fd0373d5dad77e0d30b023ce096cc04 Mon Sep 17 00:00:00 2001 From: pagh-agent Date: Sat, 21 Nov 2026 21:30:32 +0300 Subject: [PATCH 12/12] terminal: forward close/respawn through the boxed frame source MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `KernelFrame` holds `Box`; the blanket impl forwarded only `poll` and `with_pixels`, so `close`/`respawn` were served by the trait's DEFAULT bodies (`Ok(())` / `Err(Ended)`). The real device was never touched: the Enter-restart logged "devices closed → input reopened" (that part is a concrete `KeyForwarder`) and then failed instantly with the generic Ended message, which looked exactly like a kernel refusal but came from the client. The blanket impl now forwards both methods, and a test pins it: a boxed mock source must close and respawn for real (fresh generation, Drawn again). Without this, every restart attempt after `exit` was a no-op dressed as ENODEV. 175 host tests green. --- rust-apps/pagh-terminal/src/kernelsession.rs | 12 +++++++++ .../pagh-terminal/tests/kernel_session.rs | 26 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/rust-apps/pagh-terminal/src/kernelsession.rs b/rust-apps/pagh-terminal/src/kernelsession.rs index 887d7d0e..e81a22a6 100644 --- a/rust-apps/pagh-terminal/src/kernelsession.rs +++ b/rust-apps/pagh-terminal/src/kernelsession.rs @@ -275,6 +275,18 @@ impl FrameSource for Box { fn with_pixels(&mut self, f: &mut dyn FnMut(&[u8])) -> Result<(), VtFbError> { (**self).with_pixels(f) } + + // Проброс обязателен: без него `Box` (как в bin) берёт + // ДЕФОЛТНЫЕ `close`/`respawn` из трейта, и respawn молча отвечает `Ended`, + // не доходя до настоящего устройства — «окно перезапускается и сразу + // умирает» без единой ошибки от ядра. + fn close(&mut self) -> Result<(), VtFbError> { + (**self).close() + } + + fn respawn(&mut self) -> Result<(), VtFbError> { + (**self).respawn() + } } /// `read()`-fallback поверхности: `pread` заголовка + пикселей. diff --git a/rust-apps/pagh-terminal/tests/kernel_session.rs b/rust-apps/pagh-terminal/tests/kernel_session.rs index 0f524d5f..5d9e78b0 100644 --- a/rust-apps/pagh-terminal/tests/kernel_session.rs +++ b/rust-apps/pagh-terminal/tests/kernel_session.rs @@ -606,6 +606,32 @@ fn a_finished_session_restarts_in_the_same_frame() { ); } +/// `Box` (как в бинаре) обязан пробрасывать close/respawn в +/// источник: дефолт трейта отвечает `Ended`, и окно «перезапускается и сразу +/// умирает» без ошибки ядра. +#[test] +fn boxed_source_forwards_close_and_respawn() { + let mut fb = MockFb::new(info(2, 2, 10), (0, 0, 0)); + fb.failure = Some("ended"); + fb.fail_after = 2; + let boxed: Box = Box::new(fb); + let mut frame = KernelFrame::open(boxed).expect("open"); + let theme = Theme::default(); + let mut canvas = Canvas::new(2, 2, theme.bg); + frame.draw_if_changed(&mut canvas, &theme).unwrap(); + assert!(frame + .draw_if_changed(&mut canvas, &theme) + .unwrap_err() + .is_ended()); + frame.close_source().expect("close through the box"); + let info = frame.respawn().expect("respawn through the box"); + assert_eq!(info.generation, 1); + assert_eq!( + frame.draw_if_changed(&mut canvas, &theme).unwrap(), + Draw::Drawn { generation: 1 } + ); +} + /// Переоткрытие ввода после `ENODEV`: пишем уже в новую сессию. #[test] fn input_device_is_reopened_for_the_new_session() {