Skip to content

terminal: attach the window to the kernel shell session by default - #147

Merged
ccclosed merged 17 commits into
devfrom
feat/terminal-kernel-client
Nov 22, 2026
Merged

ccclosed merged 17 commits into
devfrom
feat/terminal-kernel-client

Conversation

@ccclosed

Copy link
Copy Markdown
Owner

Что это

Оконный режим терминала по умолчанию — attach к настоящей kernel-shell-сессии
ядра. Раньше окно спавнило приватный userspace-shell (--shell-child:
help/ls/cd/pwd/echo/cat/uname/clear/exit) и потому не могло показать ни df,
ни ps, ни ppkg/lxrun/disk/nano, ни history/редактирование строки.

Теперь pagh-terminal --socket PATH (без --vt/--mirror-vt/--pipe-shell/
--demo-shell) открывает /dev/vtfb1 (ioctl 0x4700 → 24 байта LE
{width,height,stride,bpp=32,generation}, mmap(PROT_READ,MAP_SHARED)) и
/dev/vtinput1, блитит изменившийся по generation кадр в окно и передаёт
клавиши как VT-байты (keys::encode_key). Клиент рендерит и передаёт ввод —
команды, эхо, редактирование и scrollback делает ядро. Ничего не имитируется.

Контракт (не менялся)

путь режим назначение
/dev/vtfb1 read-only пиксельная поверхность сессии; ioctl 0x4700, generation растёт на flush, ENODEV после exit, read() fallback = заголовок + пиксели
/dev/vtinput1 write-only VT-байты (тот же формат, что /dev/vtinput)

Поведение

  • Кадр: ioctl на каждом витке (24 байта), блит только когда generation
    выросла; полный блит (частичных damage v1 не даёт; «порванный» flush'ем кадр
    лечится следующим полным). Отправка 16 мс, холостой виток 6 мс. invalidate()
    на resize/новый memfd. ShmSurface — если композитор объявил bit 2, иначе
    полный кадр.
  • Масштаб: окно ≥ поверхности → 1:1 по центру без ресемплинга; окно меньше →
    пропорциональный nearest-neighbour downscale по центру с полями фона. Обрезки
    нет (спрятать вывод хуже, чем потерять строку пикселей), апскейла нет (мыло
    хуже чёткого центрированного кадра).
  • Клавиши: KeyModes::default() (пиксельная поверхность не несёт DEC-
    режимов), release/модификаторы → пусто, Ctrl+C — байт 0x03, сигналы
    доставляет ядро.
  • exit в сессии (ENODEV): в окне «the shell session has ended / relaunch
    to reconnect», пауза 1.5 с, окно закрывается. Реконнект = перезапуск окна
    (сессию спавнит ядро на первом open); отдельный prompt-UI в пиксельном
    зеркале в этом этапе не делался — это осознанный выбор, описан в TERMINAL.md.
  • Ошибки: устройств нет (ENOENT) → честная строка в stderr + откат на
    прежнюю pipe-сессию; устройства есть, но ioctl/mmap/read/write ломаются →
    честное сообщение в окне + код 2, без отката в демо; mmap недоступен →
    задокументированный read() fallback; короткий кадр → ShortRead.

Как это тестируется без ядра

lib.rs — #![forbid(unsafe_code)], поэтому mmap/ioctl живут только в
src/bin/pagh-terminal/devfs.rs, а вся логика — в src/kernelsession.rs за
трейтами FrameSource/InputSink. Host-тесты (tests/kernel_session.rs, 15)
гоняют generation-гейт, блит 1:1/downscale/letterbox, invalidate, short frame,
ENODEV/IO, клавиши, FileInput, read()-fallback на обычном файле, рендер
сообщения, --help, откат на pipe-сессию и честную ошибку без композитора.

Гейты (локально)

cd rust-apps/pagh-terminal
cargo fmt --all -- --check        # ok
cargo test                        # 159 passed, 0 failed (80 unit + 79 integration)
tools/build-static.sh             # static-pie x86_64-musl, 0 INTERP
cd ../.. && tools/build-rust-app.sh rust-apps/pagh-terminal   # ok

Kernel-гейты не трогались: src/** этим PR не изменён. Версия не бампалась.

Честные остатки

  • Live-QEMU не прогонялся. Kernel-сторона контракта реализуется
    параллельно и в base (dev) её ещё нет; kernel-ветка
    feat/terminal-kernel-session не найдена на origin (git ls-remote:
    только dev, main, integration/*, postmerge/desktop-dev), так что
    собрать ядро с устройствами было не из чего. Первый live-прогон должен
    подтвердить три пункта: generation растёт на flush, mmap-пиксели видны
    клиенту, ENODEV после exit доходит до окна как «сессия завершена».
  • Нет PTY/termios, TIOCGWINSZ/SIGWINCH (размер знает только ядро), terminal
    job-control; Ctrl+Z — байт в /dev/vtinput1.
  • Пиксельная поверхность не несёт DEC-режимов → стрелки всегда normal.
  • Одна сессия на окно; scrollback/selection остаются в ядре, колесо/протяжка
    в окно не транслируются.
  • Демо/pipe-пути сохранены, но теперь явные (--demo-shell, --pipe-shell);
    три e2e-теста, которые их проверяют, передают флаг вместо старого дефолта.

Notes: ~/.cache/pagh-agent-notes/qterm-client.md

pagh-agent added 2 commits November 19, 2026 14:00
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.
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.
@ccclosed
ccclosed force-pushed the feat/terminal-kernel-client branch from 4b299e8 to 8fd9fa1 Compare November 19, 2026 11:03
Updating the branch from dev failed only in one place: the import block of
rust-apps/pagh-terminal/src/bin/pagh-terminal.rs. Both sides grew new imports at
the same spot — this branch needs `client::ShmFrame` and the `kernelsession`
items for the default kernel-session window, dev needs `cell::{CELL_WIDE,
CELL_WIDE_CONT}`, `font::{CELL_H, CELL_W}`, `render_screen_into_cleared`,
`screen::CursorStyle`, `{Attrs, Cell, Screen}`, `Damage` and `Rect` for its
cell-run widget damage. The resolution keeps both sets; nothing was dropped.

Everything else merged cleanly and both features are intact:
  * kernel-session attach (this branch): `--vt-fb`/`--vt-input`,
    `--pipe-shell`/`--demo-shell`, `run_kernel_session` + `devfs` (ioctl 0x4700
    / mmap / read fallback), generation-gated blit into the window;
  * dev #161/#164/#155/#158: cell-run damage renderer in the text modes, the
    opt-level/row-store changes, pagh-ui damage/layer updates, double-click and
    lxrun changes — the text paths keep dev's new damage rendering, the pixel
    blurbs of the kernel session are unaffected.

Gates after the merge: `cargo fmt -p pagh-terminal -- --check` (and
`-p pagh-ui`), `cargo test` in the terminal crate (169 tests) and in pagh-ui
(140), static musl build via tools/build-rust-app.sh (static-pie, no INTERP).
`cargo fmt --all --check` in either crate also walks the path-dependency
pagh-desktop, whose src/server.rs is byte-identical to origin/dev and not
rustfmt-clean under this toolchain; that drift is dev's, is outside this PR's
write scope and is left untouched.
@ccclosed
ccclosed force-pushed the feat/terminal-kernel-client branch from 2a6bff9 to 129fbad Compare November 21, 2026 11:32
@ccclosed

Copy link
Copy Markdown
Owner Author

Sync with dev (1e8b077) — конфликт разрешён

git merge origin/dev дал единственный конфликт: блок импортов в
rust-apps/pagh-terminal/src/bin/pagh-terminal.rs. Обе стороны наращивали
импорты в одном месте — ветка берёт client::ShmFrame и kernelsession::* для
attach-режима, dev — cell::{CELL_WIDE, CELL_WIDE_CONT}, font::{CELL_H, CELL_W},
render_screen_into_cleared, screen::CursorStyle, {Attrs, Cell, Screen},
Damage, Rect для cell-run widget damage. Разрешение — объединение обоих
наборов, ничего не потеряно.

Автоматически слились без конфликтов и сохранены обе стороны: --vt-fb/
--vt-input/--pipe-shell/--demo-shell + run_kernel_session/devfs
(ioctl 0x4700/mmap/read fallback, generation-блит) и dev #161/#164/#155/#158
(cell-run damage в текстовых режимах, opt-level/row-store, pagh-ui
damage/layer, double-click, lxrun). Пиксельный блит kernel-session от нового
текстового damage-рендерера не зависит.

Гейты после merge:

  • cargo fmt -p pagh-terminal -- --check — ок; cargo fmt -p pagh-ui -- --check — ок.
  • cargo test в rust-apps/pagh-terminal — 169 passed, 0 failed
    (80 lib + 7 bin + остальные наборы; kernel-session — 15).
  • cargo test в rust-apps/pagh-ui — 140 passed, 0 failed.
  • tools/build-rust-app.sh rust-apps/pagh-terminal — static-pie x86_64-musl,
    0 INTERP.
  • CI на 129fbad8: kernel / host-tests / static-policy / docs-claims — все pass.

Замечание (не моё и вне scope PR): cargo fmt --all --check в обоих крейтах
идёт и по path-зависимости pagh-desktop, где src/server.rs побайтово равен
origin/dev и не rustfmt-чист под этим тулчейном. Эту дрейф-строку не трогал.

Live-QEMU по-прежнему не прогонялся: kernel-ветка feat/terminal-kernel-session
теперь запушена (289164b2) и содержит src/drivers/{session,vtfb_abi,offscreen}.rs,
так что live-интеграция разблокирована — но это шаг координатора, не этого PR.

pagh-agent and others added 5 commits November 21, 2026 15:19
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.
…derr

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.
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).
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.
@ccclosed

Copy link
Copy Markdown
Owner Author

Live acceptance on #148 (KVM, release kernel) — evidence in ~/.cache/pagh-agent-notes/q147-live/

Image: release pagh.elf sha256 19d13cc1bde0eda671a1dc2f1d988dc11ccd1eb0a485dc0230495d3c7376fe5d
built in live/q147-kernel-session = origin/dev (contains #148) + this branch,
staged into a kernel-formatted ext2 carrying /mnt/{pd,pagh-files,pagh-terminal}.
QEMU -enable-kvm -cpu host -m 5120M, lock /tmp/pagh-e2e.lock, tools/e2e.py desktop.
Full write-up: q147-live/EVIDENCE.md; per-check table: q147-live/checks.tsv.

(1) /dev/vtfb1 open + mmap(MAP_SHARED) + generation — PASS

client.log (dumped from ext2 with debugfs after the guest stopped):

kernel surface /dev/vtfb1: mmap 4096000 bytes PROT_READ|MAP_SHARED (ioctl 0x4700 1280x800 stride 5120 bpp 32)
kernel session 1280x800 (stride 5120, generation 8) on /dev/vtfb1
kernel frame generation 9 drawn … 252 drawn frames, generations 9..1161

No read() fallback line. window-01-prompt.png shows the kernel session banner
in the window.

(2) df / ps / nano in the window — PASS

window-02-df.png (df table), window-03-ps.png (df + ps: PID/TTY/TIME/COMMAND,
kernel session shell…init), window-04-nano-edit.png (nano with the typed line
nano works in the kernel session, sidebar + ^G Save … ^Q Quit),
window-05-nano-saved.png (^S), window-06-back-to-prompt.png (^Q),
window-07-nano-content.png (cat shows the saved file), window-08-help.png
(kernel-shell command list).

(3) exit → ENODEV — PASS; respawn on a second window — NOT captured

kernel session ended (the shell exited); window closed in client.log;
window-09-session-ended.png shows the honest notice («the shell session has
ended … relaunch pagh-terminal to reconnect»); window-10-window-closed.png is
the empty desktop. A second desktop launch was refused with
duplicate window (3): окно 201 уже существует (the compositor keeps the dead
client's window id), and a shell-started second client cannot be typed into
(finding 1 below). Kernel-side respawn (session::note_open(1) on the first
open) is #148's code and its unit tests; the client half after exit is proven.

Findings — ABI/desktop, not this client (details in EVIDENCE.md)

  1. Window input dies when the console has a foreground compat process.
    vtinput::write_session sends the bytes to FG_PID's stdin when
    FG_PID != 0 && compat_exists(FG_PID); shell/commands.rs sets FG_PID for
    a foreground lxrun. The shipped recipe (desktop-autorun: lxrun /mnt/pd …
    foreground) therefore makes the window's keyboard inert — evidence
    canonical-foreground/window-01b-foreground-df.png: canonical autostart,
    df typed, no echo/output; the identical typing after bg works. The client
    writes to /dev/vtinput1 exactly as the contract says.
  2. TOSTOP stops a desktop-launched child on its first stderr write
    ([tty] background write by pgid 7 … SIGTTOU). Mitigated in the client by
    --log-file (all diagnostics, including fatal startup errors).
  3. vtfb1 has no seqlock: a frame copied mid-flush stays torn until the next
    flush (client repaints fully then; screenshots take one extra Enter first).
  4. Kernel O_APPEND is accepted and ignored — the client seeks to end so a
    relaunch does not overwrite the previous run's log.

Gates

cargo fmt -p pagh-terminal -- --check and -p pagh-ui clean; 172 host
tests in rust-apps/pagh-terminal, 140 in rust-apps/pagh-ui; static
pagh-terminal = static-pie x86_64-musl, 0 INTERP
(tools/build-rust-app.sh rust-apps/pagh-terminal).

`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.
pagh-agent and others added 4 commits November 21, 2026 18:54
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<File>`), 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.
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<File>`, 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.
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.
@ccclosed

Copy link
Copy Markdown
Owner Author

Respawn/reopen: клиентская часть сделана; оставшийся блокер — kernel-путь

(a) duplicate-window при respawn — закрыто в клиенте

exit больше не закрывает окно и не требует второго запуска приложения:

  • ENODEV → окно остаётся, в нём честная плашка «the shell session has ended —
    Press Enter to start a new session in this window»;
  • Enter → close-all-then-open-all: InputSink::close + FrameSource::close
    (снять mmap, закрыть оба fd), затем respawn ввода и поверхности;
  • окно и window_id те же — второго create нет, поэтому duplicate window
    при respawn невозможен по построению;
  • порядок несущий: закрыть старые fd до любого нового open, иначе поздний
    close роняет счётчик открытых устройств сессии до нуля и ядро просит новую
    сессию выйти (это ловилось в live и исправлено).

Коммиты: 63697811, f9ced4f2, 9925315a, a0be8ffe. Тесты крейта — 174
(restart в том же холсте со свежим generation; хуки close/reopen; порядок
close→open), musl static-pie собран.

(b) live: где именно останавливается respawn

q147-live/respawn-attempt/client.log:

kernel surface /dev/vtfb1: mmap 4096000 bytes PROT_READ|MAP_SHARED (ioctl 0x4700 1280x800 stride 5120 bpp 32)
kernel session 1280x800 (stride 5120, generation 8) on /dev/vtfb1
kernel session ended (the shell exited); window kept, press Enter to restart the session
restart: devices closed, reopening input
restart: input reopened, reopening the surface
restart: surface not up yet (…ENODEV…), retrying     ×3
cannot restart the session: … ENODEV …

— ввод после exit ядро принимает (новый open(/dev/vtinput1) поднял
сессию), а open/ioctl /dev/vtfb1 в том же процессе продолжает отвечать
ENODEV. Kernel-selftest (src/test.rs, «a repeated open respawns the session»)
при прямом session::note_open(S) сессию поднимает, значит расхождение в
device-пути: io_sys::open_path → session::note_open(1) →
framebuffer::init_session(1) / vtfb_info (live(1)). Это #148/#169 (kernel),
не клиент.

Скриншоты попытки: q147-live/respawn-attempt/window-04-session-ended.png (плашка
в живом окне), window-05-respawned.png, window-06-respawn-uname.png.
Проверка «exactly one window was ever created» — PASS (дубля окна нет).

Гейты / CI

cargo fmt -p pagh-terminal -- --check и -p pagh-ui — чисто; terminal 174,
pagh-ui 140 тестов; static musl (0 INTERP). CI на d5410f65: kernel /
host-tests / static-policy / docs-claims — все PASS, PR MERGEABLE.

Kernel-правок в PR нет: input-маршрутизация — #169, respawn-путь поверхности —
его же область (точный указатель — в q147-live/EVIDENCE.md).

ccclosed and others added 2 commits November 21, 2026 20:47
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.
pagh-agent and others added 2 commits November 21, 2026 21:30
`KernelFrame` holds `Box<dyn FrameSource>`; 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<FileInput>`) 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.
@ccclosed

Copy link
Copy Markdown
Owner Author

Финальный live Enter-respawn на dev+#174 — PASS (15/16, единственный FAIL — устаревшая проверка драйвера)

Ветка ребейзена на dev с #174 (597c8441), каноническая foreground-форма
(композитор — foreground-совместимый job, без bg), один клиент, один
create. Evidence: ~/.cache/pagh-agent-notes/q147-live/canonical-foreground-final/.

kernel surface /dev/vtfb1: mmap 4096000 bytes PROT_READ|MAP_SHARED (ioctl 0x4700 1280x800 stride 5120 bpp 32)
kernel session 1280x800 (stride 5120, generation 8) on /dev/vtfb1
kernel session ended (the shell exited); window kept, waiting for Enter to restart the session
restart: devices closed, reopening input
restart: input reopened, reopening the surface
kernel session restarted in the same window (1280x800, stride 5120, generation 199)
  • serial.log: [DIAG] window session=1 command=df, command=ps, command=exit,
    command=uname — все команды выполнила сессия 1 ядра (ввод без workaround).
  • После рестарта — 44 новых кадра (последний generation 293); окно то же,
    ноль duplicate window / not owner, один execve клиента.
  • window-04-session-ended.png — плашка в живом окне; window-05-respawned.png —
    новая сессия (баннер shell) в том же окне; window-06-respawn-uname.png — ввод
    после рестарта (uname в kernel-shell отсутствует, ответ честный
    command not found, но команда выполнена сессией 1 — см. DIAG).
  • Единственный FAIL в checks.tsv — устаревшее ожидание «счётчик generation
    начинается заново»: счётчик живёт на поверхности, а поверхность
    переиспользуется (кадры закреплены), поэтому 199 после 8 — норма. Проверка
    снята; содержательные проверки рестарта — PASS.

Diff (по решению lead)

  1. Убран параллельный awaiting_respawn/notice_pending.
  2. wait_for_restart + draw_notice_frame — имя, сигнатура, текст плашки и
    семантика клавиш как в terminal: independent sessions, pointer UX and honest lifecycle (stage 4) #167 (Enter/Space → новая сессия в этом окне, Esc →
    закрыть). terminal: attach the window to the kernel shell session by default #147 несёт минимальную совместимую версию, terminal: independent sessions, pointer UX and honest lifecycle (stage 4) #167 расширяет тот же
    путь без смены семантики.
  3. Box<dyn FrameSource> пробрасывает close/respawn — раньше дефолты
    трейта отвечали Ok(())/Err(Ended), и рестарт «умирал» без участия ядра.
    Это была последняя причина, по которой live не проходил даже с kernel: reopening a terminal window cancels its pending session exit (vtfb1 respawn) #174; тест на
    проброс добавлен.

Гейты / CI

cargo fmt -p pagh-terminal / -p pagh-ui — чисто; 175 тестов terminal
(+1 на проброс boxed-источника), 140 pagh-ui; tools/build-rust-app.sh —
static-pie x86_64-musl, 0 INTERP. CI на 597c8441: kernel / host-tests /
static-policy / docs-claims — все PASS, MERGEABLE. Не мержил.

@ccclosed
ccclosed merged commit 9bacc74 into dev Nov 22, 2026
8 checks passed
@ccclosed
ccclosed deleted the feat/terminal-kernel-client branch November 22, 2026 06:23
ccclosed added a commit that referenced this pull request Nov 22, 2026
…indow

Adds 'tools/e2e.py termwindow', the stage-2 acceptance that #147/#169 made
possible: the shipped pagh-desktop + pagh-terminal pair runs on the real
fbdev/evdev/PDP path, and the window itself is kernel-shell session 1
(/dev/vtfb1 pixels + /dev/vtinput1 keys), so every command is the kernel
shell's own code, not a userspace imitation.

The compositor is started from /mnt/etc/autorun — the shipped
desktop-autorun recipe. That is not cosmetic: the launch-target spec
contains '{socket}', and typing shifted braces through QMP left a stuck
modifier under TCG, so the next 'c' reached the guest as a real ^C. With
autorun, the only keys on the wire are the commands under test.

Per command the mode records one PNG (what a human sees) and one
'[DIAG] window session=1 command=…/done=…' serial pair (the kernel's own
evidence that the line reached and returned from session-shell). It fails
if any kernel-shell output appears on serial — that would mean the command
executed in the boot shell instead — reads the nano buffers back out of
the ext2 image with debugfs, and uses the kernel's 'stuck in syscall read'
watchdog line to know when the Linux editor is ready for keys.

Covered: df, ps, ps -ef, id, id -un, groups, ls -la /mnt, disk list, clear,
help, kernel nano (edit/Ctrl+S/Ctrl+Q), ppkg update, ppkg install nano
fastfetch ncurses-base, bare fastfetch (PATH fallback without lxrun) and
lxrun nano (Ctrl+O/Enter/Ctrl+X). A 256 MiB volume is created because the
64 MiB desktop image cannot hold ppkg install.

Known gap, reported rather than papered over: the Linux (ncurses) nano
opens and renders, and an earlier run saved its file (read back from ext2),
but in later runs the editor parked in read(2) without receiving the
Ctrl+O/Enter/Ctrl+X chords — termios/raw-mode, i.e. the named stage-3
PTY/job-control work, not window routing.

Docs: tools/README.md bullet + terminal-session.md §7.
ccclosed added a commit that referenced this pull request Nov 22, 2026
The kernel now keeps winsize/SIGWINCH per console session, but the window client
never told it the window changed size: a TUI inside the session could not react
to a compositor resize.  On every Configure (and once at startup) the client
converts its client area to the kernel cell grid (8x18 px, integer division,
one-cell floor, u16 clamp) and issues TIOCSWINSZ on /dev/vtinput1.  The kernel
stores the session's size and queues SIGWINCH to its foreground group; an
unchanged size is a no-op on both sides.

The ioctl stays in the devfs unsafe module; the cell arithmetic is a pure
host-tested function (tests/kernel_session.rs).  The client documents the resize
contract and the honest boundary: winsize is the app-facing cell size, the
pixel surface is still screen-sized and scaled by the client.

Stacked on origin/feat/terminal-kernel-client (PR #147) so the live window can
be driven end to end before #147 merges; rebase once it lands in dev.
ccclosed pushed a commit that referenced this pull request Nov 22, 2026
Sync with dev=c1e80933 (#147/#175/#176/#178: console grid from real
framebuffer, scrollback/selection, rubberband fullscreen, os-identity,
docs).

Conflict: src/test.rs only — both sides appended routines/modules at the
same two places. Resolution keeps BOTH:
- dev qbug2 "console::text grid matches the framebuffer resolution"
  (console_grid_tests) and the USB "usb::BOT/SCSI/uevent layouts and
  /usb root rule" (usb_storage_prop_tests);
- both modules are present and closed; all_tests registers 126 routines.

All USB S1 files are untouched by these dev changes, and the dev
framebuffer/console/scrollback/selection/os-identity work is preserved
verbatim. AGENTS.md auto-merged and keeps the USB S1 gap text.

Post-merge evidence: gates 6/6 (host 885/0), QEMU usb-storage acceptance
46/46, release-kernel selftest 126 routines / 0 failed / 1 skipped
(NVMe absent), in one flocked run.
ccclosed added a commit that referenced this pull request Nov 22, 2026
test(live): stage 2 — full kernel shell in a real desktop window (stacked on #147)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant