The session: guidance, compaction and the terminal

Part of the Workflow Modes reference.

Guidance injection

The guidance reaches the model as pi sections (#729): named parts of the structured system prompt that pi renders after its own <cwd>, in this order, most specific last:

<gadhs-guidance>                  scope: global - the packaged digest (or guidance.global override)
<gadhs-guidance-language-X>       scope: language:X - per language detected in the cwd or a first-level directory (Cargo.toml → rust, …); on the remote, in a remote session
<gadhs-mode>                      mode: <id> - the active mode's systemPrompt
<gadhs-guidance-project>          scope: project - <cwd>/.pi/gadhs-guidance.md (trusted repos only)
<gadhs-memory>                    the governed memory's lines

pi-modes writes them into before_agent_start’s `systemPromptOptions.sections and returns no prompt. pi diffs the sections against the transcript’s current system row each turn and appends one system message patching only the changed ones; a Claude on Vertex whose catalogue entry says midConvoSystem: true receives that patch in place and keeps its cached prefix (the catalogue, #744 - Sonnet 4.6 and Haiku 4.5 refuse such a message, so for them pi replays the prompt whole, one miss per change), so a mode change costs one small message, not a re-write of the whole context. Before #729 the blocks were composed into one string and returned as the run’s forced prompt, which pi projected whole over every request: a mode change was a cache miss from byte zero (73 of 76 prompt rebuilds in one week-long session, $259); a section a later handler wrote never reached the provider - and @gotgenes/pi-permission-system writes a helper’s <tools> and <rules> as sections precisely because pi writes neither under a custom prompt, so every helper had run with no tools or rules section at all; and the transcript’s system row was not what the model saw. A block absent this turn is written empty, which pi leaves out and the diff removes: a language profile the checkout lost, the project block when trust changes, the memory block when emptied. Measured on Vertex Opus 5.5 before it landed (plan prompt-sections, U1): the patched turn read 7,537 cached tokens and wrote 62; the collapsed form read 0 and wrote 7,579.

A helper whose own prompt replaces the default (prompt_mode: replace: Explore and Research) is written none of these sections (#894). It reads and reports, and the working agreements, the language profiles, the mode’s text and the memory are written for a session that edits and commits; its own prompt already carries the project’s AGENTS.md. pi-subagents puts <active_agent name="…"/> in every helper’s prompt and wraps an appending helper’s body in <agent_instructions> after it, and that is how pi-modes tells the two apart. The general-purpose helper appends, edits and commits, and keeps every section. Pins: test/session-wiring.test.ts (both modes, a main session with a prompt of its own, and both markers read from the pinned pi-subagents' source) and consumer-sim’s row on a real Explore helper’s system row.

Nothing is written to disk, so nothing drifts — pi extension update is the sync. /gadhs-init scaffolds a project-owned AGENTS.md skeleton (refuses to overwrite). With no blocks configured no section is written and pi’s own prompt stands. Inside the sections, a literal <gadhs- or </gadhs- is broken by a zero-width space, so it reads the same but can never be taken for a section’s edge (#443). A monorepo with no root manifest gets each language its first-level directories declare (api/pom.xml, web/package.json).

Compaction: pi’s summarizer, thinking off

pi summarizes a session on the session’s own model, at the session’s own thinking level, inside a budget of 0.8 x compaction.reserveTokens (13 107 tokens by default). On a reasoning model at a high effort the thinking spends that budget before the summary is finished; pi sees a length stop and - correctly - refuses to persist a partial summary, so compaction fails with "generation hit the token cap and the summary is incomplete." Observed live on claude-fable-5-1 at high; lowering the level fixed it. The variable was thinking, not the model.

pi-modes therefore handles session_before_compact by running pi’s own compact() — its prompt, its update-summary flow, its split-turn handling, its fail-closed rule on length — with two inputs changed:

  • the thinking level is off;

  • the reserve pi sizes the summary budget from is floored at 65 536 tokens (a 52k summary budget; a larger operator setting is kept, and pi still caps at the model’s maxTokens), because a days-long session’s update summary — the previous summary re-emitted with everything since — does not fit pi’s default budget with thinking off or on.

The model stays the session’s: the summary is the session’s memory, written by the model that made it. The stream goes through the composed provider with auth resolved as pi resolves it, so the request differs from pi’s own only in the missing reasoning and the larger output budget.

When the hook hands back undefined, pi’s default runs: the model has no thinking to turn off (then the two paths are identical), the provider or its auth is missing (pi reports that itself), or our attempt failed - one warning names the reason, and pi’s own attempt surfaces its own error rather than ours masking it. A cancelled compaction is silent.

When the provider refuses the request

One failure is not a failure to answer but a refusal to be asked. A provider’s policy classifier can block the summarization request itself: Anthropic’s read a long session - every cold review, every judge verdict, quoted verbatim in tool results - as "duplicating model outputs" and answered "This request was blocked as it seems to violate Anthropic’s Terms of Service restrictions on reverse engineering or duplicating model outputs." That is deterministic on the content: the same call on the same provider fails the same way every time, and pi’s default compaction is the same call: without a fallback, our attempt and pi’s fail as a pair on every turn, and the way out is /model to another family, /compact, /model back — by hand.

So a refusal (isPolicyRefusal, by vocabulary — "terms of service", "usage policy", "request was blocked", "violate" — not the sentence) is the one case where the hook does not hand back to pi:

  • it writes the summary once more on the fallback summarizer, compaction.fallbackModel in the modes overlay (default vertex-gemini/gemini-4-hydrogen: another provider family, a window every session fits, cheap), same preparation, thinking off;

  • one warning names which provider refused and which model wrote the summary;

  • with the fallback null, unknown to the registry, or the session’s own model, the warning names the way out by hand; with the fallback failing too, it carries both reasons and pi’s default runs next.

A transport error or a length stop is not a refusal and takes pi’s default path, on the session’s model.

Pins: test/compaction.test.ts (same preparation, same auth path, the session’s model, off, each hand-back, and the refusal: recognised by vocabulary, retried once on the fallback with off and the floored reserve, one notice, and each way the fallback can be missing or fail), test/config.test.ts ("the compaction block"), test/wiring-lifecycle.test.ts ("compaction hook wiring"). Verified live 2026-09-01: the requests pi sent carried no reasoning, the responses were text-only stop, and pi recorded the compaction as fromExtension.

Switching to a model the context does not fit

pi’s answer to a context that no longer fits is a compact-and-retry on the current model. Switch a long session from a 1M-window model to a 262k one and that answer is the problem: the turn is a 400, the recovery’s summary request carries the same context and is a 400, /compact is the same call, and the session is stuck on that model. Nothing in pi warns at the switch - model_select is notification-only, and pi does not compare the context to the new window. (Two further gaps made it worse on the agency’s own providers and are fixed in @gadhs/pi-vertex: messages stamped with the wire’s model name rather than the session’s id, which made pi skip the recovery as "a different model’s error", and catalog windows larger than what Vertex accepts - see Models on Vertex AI (@gadhs/pi-vertex).)

pi-modes hears the switch the moment after it happened. When the context does not fit - the line is pi’s own compaction threshold, tokens > contextWindow - 16 384 (pi’s default reserve), because above it pi compacts on arrival and that compaction is the deadlock - it says so by name:

Context is ~812k tokens; vertex-maas/grok-4.20-reasoning accepts 262k. Switching
from vertex-anthropic/claude-fable-5-2 here will fail: the next turn is a 400,
and pi's recovery compacts on vertex-maas/grok-4.20-reasoning itself, which
cannot fit either. /new starts fresh; switching back and running /compact there also
works.

Two ways out, and it names both. /new is the clear command - pi’s own, a fresh context - and stays yours to type (a fresh session needs a command context pi does not give an event handler). Compact first it can do for you: after a /model switch from a model the context fits, a dialog offers "Compact on <previous> first, then switch to <next>`" or "Keep `<next>`"; the first switches back, runs `/compact there (where the summary can be written), and switches again when it completes. A compaction that fails leaves you on the previous model and says why; a switch back that fails leaves you where you are. Model cycling (Ctrl+P) and session restore only warn - a dialog on every cycle step is worse than the 400 - and a context pi cannot yet estimate (right after a compaction) is not judged.

Pins: test/context-fit.test.ts (the fit line, the dialog’s presence per source and previous model, each route’s calls and its failure handling). Observed live 2026-09-07 over pi’s RPC: 121k tokens on Haiku, set_model to vertex-maas/gpt-oss-120b (131k): the warning, the dialog, the switch back, compaction_end without error, the switch forward, and the next turn answered on gpt-oss at 43k input.

Dropping a file onto the terminal

A terminal has no drop protocol (#340). Dropping a file types its path, quoted ('/home/u/a b.png'), backslash-escaped (/home/u/a\ b.png) or as a file:// URI, and pi’s ctrl+v of a screenshot inserts the path of a temporary PNG. Left alone, the model would get a path and never the picture. So when a prompt you submit names an image file on this box, pi-modes sends the image with it, through pi’s input event. The path stays in the text, so the agent knows which file it was.

On Windows (#582) a drive path is a drop too, quoted or bare, with either slash ("C:\Users\me\a b.png", C:/Users/me/a.png). Its backslash is a separator, not an escape. A file:///C:/…​; URI is that drive path, and a Git Bash path (/c/Users/me/a.png) is the drive path Git Bash means.

  • An image is a path ending .png, .jpg, .jpeg, .gif or .webp whose bytes are a PNG, JPEG, GIF or WebP. The bytes decide the type: a .png holding a JPEG goes as image/jpeg; one holding text is not attached. The caps are 5 MiB an image and 20 MiB for the prompt’s images together (counting any an earlier handler attached). An image over a cap stays a path. pi then resizes what it is given, as it does for its own pastes.

  • Any other file stays a path. The agent opens it with read, and the read gate decides as usual.

  • A folder stays a path too (#351). The notice names it with how many entries it holds (named: shots (folder, 12 entries)), counted up to 1000 (1000+ entries beyond). Nothing in it is read or attached: the agent lists it if it needs to. A folder named like a credential store is named without being opened.

  • Never attached: an image named like a credential file (the read gate’s list: .env*, key and certificate suffixes, id_* keys, names holding credential or secret, .netrc and its kin), and any image when the session’s model takes no image input.

  • Not copied: the file is already on this box, unlike a phone’s (cf. the pivot client’s attach, Working remotely). If you edit the file before the agent reads it, the agent reads the new contents.

  • Only what a person sent: a message an extension sends is left alone. pi runs a registered slash command before any input handler, so /pending approve #1 /tmp/a.png attaches nothing.

The judge is not consulted: you typed or dropped the path, which is the consent. One notice per prompt says what happened, in the order the prompt named the files:

attached: shot.png (image, 212 KiB) · named: notes.md (text, 3 KiB) · not attached: big.png (over 5 MiB per image) · missing: /tmp/x.txt

missing is reported only for a quoted or file:// path, the shapes a drop or a paste writes. A bare path that does not exist (/api/v1/users in prose) is prose. A file that cannot be read fails open to its path, so this never blocks a prompt. dropToAttach: false in the modes overlay turns it off (tuning).

Pins: test/drop.test.ts (each drop shape as a property, Linux’s and Windows' grammar each pinned by name so both run on every host, the magic bytes, each cap at its boundary, the credential names, a folder’s count at its cap, the receipt; a real pi session where /pending carrying an image path reaches no input handler, and its control where the same path in a plain prompt reaches the model as an image).

The turn recap

After an autonomous run you come back to a long transcript (#352). So at the end of every turn, pi-modes adds one line where the turn ended, ending with the time it ended (#646). A turn that did enough to need a card, at least 3 tool calls or 20 seconds, reads as one:

recap · 4 files · 11 commands · tests passed · 1 denied · 1 queued · 1 helper · commit 3f241e5 · MR !280 · 6 m 12 s · +$0.84 · 14:05

A shorter turn reads as its end time and length alone, 14:05 · 8 s. Either way the last line of the transcript says when the agent stopped, so a glance tells you whether it is waiting for you. The time is local: 14:05 today, Oct 31 14:05 on another day, 2025-10-31 14:05 in another year, as the phone shows it. A recap written before #646 has no end time and shows none.

Each part of the card appears only when it is not zero, and the spend only from half a cent, so it never reads +$0.00. One part the example lacks: N deferred, the steps the judge left to you. Expanded (pi’s ctrl+o), the lists follow: the files, the commands (first lines, in order), each test run passed or failed, the refused and queued steps with their reasons, the helpers, the commits and the MRs.

  • Files: the paths of edit and write calls that succeeded, relative to the working directory.

  • Commands and test runs: every shell command that ran. A command is a test run when any of its && / || / ; segments starts with vitest, pytest, go test, pnpm test, npm test, cargo test or node --test (after npx, pnpm exec or environment assignments). It passed or failed as pi reports it. With several runs, the line gives the last run’s outcome, the state you come back to.

  • Commits and MRs: read from the command’s output: git’s own [branch sha] line, and an MR’s GitLab URL (…/-/merge_requests/N), which glab mr create prints, as does a push to a branch with an open MR.

  • Refused and queued: every non-allow trace of the turn, including the workflow guards'.

  • Time and spend: from the turn’s start to its end, and what the session spent in between (the figure the spend cap reads); then the clock time it ended.

Only what ran is counted: pi reports a tool result only for a call that executed, so a step the permission system blocked is a refusal on the card, never a failed test run. The recap is a custom entry, which pi keeps out of the model’s context, so it costs no tokens and the agent never reads it. recap: false in the modes overlay turns it off (tuning).

Pins: test/recap.test.ts (the ledger over scripted turns: files, commands, test runners per segment, the commit line and the MR URL, the trace counts, helpers, time, spend; the threshold; the wording; a result of an unknown shape counted without a throw; the end time’s three forms and the short turn’s line), test/session-wiring.test.ts ("the turn recap through the real hooks", a short turn’s entry included).

Time on the issue

pi records how long the agent worked on an issue in GitLab’s own time tracking, the Time tracking box in the issue’s sidebar (#576). Nobody types anything, and nothing is estimated.

  • What is measured: each turn’s time from the recap, from its start to its end. A helper’s time lies inside the turn that ran it. The time between turns, while you read, think or are away, is in no turn and is never counted.

  • Which work item: a turn counts toward the branch the session’s directory was on when the turn ended. A turn on main, on a detached HEAD or outside a repository counts toward nothing.

  • Which issue: the issues the branch’s commits close, Closes #N on a line of its own. A branch that closes several splits the time equally, and each post names the others. Relates to is not a closure.

  • When: at the end of a turn that ran a git push that succeeded, in the session’s own directory (not after a cd elsewhere, git -C, --git-dir or --work-tree, and not a dry run). pi posts what this session’s turns on the branch add up to, less what it already posted on that issue, in whole minutes. Under a minute waits for the next push. So a re-push after review posts only the time since the last post.

  • Where it posts: GitLab’s add_spent_time on the origin remote’s host, with the summary measured by pi: N turns on <branch>, session <id>, the id’s first 8 characters; a split adds , shared with #N. Each session posts its own share; GitLab adds them up.

  • The token: the workspace’s own, GITLAB_TOKEN (or GITLAB_ACCESS_TOKEN) from pi’s environment, else the GITLAB_TOKEN line of the repository’s .env.local. It goes in the request’s header and nowhere else. Without one, pi says once that time was measured but not posted.

  • A failure: one warning naming the issue and GitLab’s status. Nothing is recorded, so the next push posts the whole difference again. The post never holds up the turn or blocks anything.

  • A git that does not answer: the post reads the branch’s commits and its remote with git, after the turn has ended, each read allowed 30 seconds. One that does not answer in that time is said, time measured, not posted yet: git log did not answer within 30 s, and logged (time-spent.skipped, reason git-unanswered); nothing is recorded, so the next push on the branch posts it. Before #766 those reads blocked pi for up to five seconds each, and one that timed out was read as "this branch closes no issue": on a loaded box the time was never posted and nothing said so. The turn’s branch is read the same way, for every turn as it ends: git is given ten seconds, pi is not blocked while it runs, and when it does not answer pi says the turn’s time is not counted (#785). Before that the read blocked for two seconds and a timeout was taken for "no branch", so a turn dropped out of its branch’s total unnoticed.

The agent never computes, adjusts or confirms the number. Each post adds a gadhs-time-posted custom entry: the branch, the issue and the total posted. Like the recap, pi keeps it out of the model’s context.

Pins: test/time-spent.test.ts (the readings; the request’s contract; the poster end to end: a first push, a second push’s difference, nothing to post, an equal split, a refused post retried, no token, unreachable; the token in no notification, record or entry), test/recap.test.ts (a turn’s branch, and which commands are a push), test/session-wiring.test.ts ("the measured time through the real hooks", a real repository).

The working line

While a turn runs, pi shows a working text. Once the turn’s first tool starts, pi-modes replaces it with what the turn is doing (#354):

running pnpm test · 42 s · 2 helpers · +$0.12
  • What is running: running <command> for a shell tool (its first line, cut to 48 terminal cells, so a wide character counts twice, control characters dropped), reading / editing / writing <file> for the file tools, the tool’s name otherwise, and thinking between tools. With several calls running at once, the newest is shown. A call another tool made (a codemode script’s) does not replace its parent’s line.

  • Elapsed: since the turn began, kept moving by a one-second timer that runs only during a turn.

  • Helpers and spend: the subagents running now, and what the turn has spent (read when a tool ends), each only when not zero.

pi’s own text stands until the first tool starts, and comes back when the turn ends. A turn with no tools never touches it. Only in the terminal: nothing is written at a headless host. workingLine: false in the modes overlay turns it off (tuning).

Pins: test/working-line.test.ts (each tool kind, the text’s parts, the newest running call, nested calls, the timer stopped at the end and on shutdown, pi’s text given back only after the line wrote), test/session-wiring.test.ts ("the working line through the real hooks").

The terminal’s title and tab follow the session

pi writes one static title — π - <session> - <dir>, the folder’s name, and π - <dir> for a session with no name (a rebranded fork’s own name in place of the π, read from pi’s package.json) — at start and on rename. With several sessions open, a tab bar cannot tell the one that is working from the one waiting for its human, which is the one thing worth knowing. So pi-modes drives two things from events pi already fires:

  • The title carries a glyph in front of pi’s own text: ◐ while a turn runs (agent_start to agent_end), ⚠ while a dialog waits for an answer (ui_prompt_start to ui_prompt_end, which pi fires for every extension prompt — the permission system’s included — and coalesces into one span), and nothing when idle, so the idle title is byte for byte pi’s own. A step waiting in /pending shows ⚠ too (#458): in auto and plan mode an undecided command is queued instead of opening a dialog, and it waits on you just the same. A dialog or a waiting step outranks work; when the last one is answered mid-turn, the glyph goes back to ◐.

  • The tab carries OSC 9;4, the progress-state sequence Windows Terminal, ConEmu and iTerm2 render as an indicator on the tab: 3 (indeterminate) while working, 4 (paused — attention) while a dialog or a queued step waits, 0 (cleared) when idle. A terminal that does not know the sequence ignores it.

  • Helpers (#786): a background helper outlives the turn that launched it, so a running helper counts as work. The tab stays indeterminate until the last one ends, and the title says how many in one character after the glyph, the glyph saying whether pi itself is busy:

    Title starts Means

    (nothing)

    idle: no turn, no helper

    ◐

    a turn is running

    ◐2

    a turn is running, and two helpers

    ○2

    no turn; two helpers still working. pi can be typed to

    ⚠

    a dialog or a queued step waits on you

    ⚠ 2

    it waits on you, and two helpers are working

    After the warning sign the count stands a space off: some terminals draw that sign two cells wide and count it as one, and drew the digit over it.

    The count comes from pi-subagents' lifecycle events on pi’s bus (subagents:started and resuming; completed, failed and resumed), so it covers a backgrounded helper to its real end. An end is counted one second late: pi-subagents announces a finished helper and then wakes the agent with its result, and without the pause the tab would go idle and ring for the moment between. "finished" rings when the turn has ended and no helper runs, not when a turn ends with helpers still at work.

  • The nudge (#342): the tab only helps if you are looking at it. pi itself sends no bell and no notification. So on the two moments that need you, something waiting on you (a dialog opening, any of them as above, or a step queued in /pending) and a turn ending with nothing open, the terminal also gets a BEL, which every terminal does something with (a sound, a flash, a mark on the tab). It also gets an OSC 9 desktop notification, which iTerm2 began and kitty, Ghostty, WezTerm and foot show: π - <session> - <dir>: waiting on you, or : finished. A VTE terminal (GNOME Terminal, Tilix: VTE_VERSION is set) shows OSC 777’s notify instead, so there the same title and words follow as one too (#350). The text is the title with control characters dropped, never the ask or a command, since a desktop notification is visible to anyone near the screen. Nothing rings while the window has focus. pi’s fullscreen mode turns on focus reporting, and a listener on pi’s raw terminal input reads it, passing every chunk on untouched. In regular mode a keystroke in the last 3 s counts as focus. Nudges less than 2 s apart ring once, so a dialog and a queued step at the same moment ring once. Answering a dialog or a queued step does not ring.

Only in the terminal: a headless host has no tab, and an OSC on a JSON or RPC stream would be corruption — nothing is written there. pi re-asserts its plain title on a session rename; the next event puts the glyph back. title.enabled: false in the modes overlay turns all three off, title.progress: false the OSC 9;4 alone, and title.nudge ("all", "asks" for dialogs and queued steps only, "off") the nudge (tuning).

Pins: test/title.test.ts (the text, the sequences, the state rule, the tracker writing only on a change, headless and disabled writing nothing; the nudge over every pair of states, its exact bytes, control characters dropped, focus from pi-tui’s reports and from keystrokes but not mouse reports, the coalescing, the levels), test/session-wiring.test.ts ("the title follows the session through the real hooks", the nudge included).

A mouse report cut in two is dropped, not typed

pi’s fullscreen mode turns on mouse reporting: every wheel tick, and every movement over the window, reaches pi as ESC [ < button ; col ; row M. pi-tui holds an unfinished escape sequence for 50 ms (a lone ESC for PI_TUI_ESC_TIMEOUT: 10 ms by default, 100 ms over SSH) and then flushes it as input. When a report is split across two reads and its tail comes later than that, the head is flushed and the tail is typed into the editor one character at a time, as ;13M5;34;13M or <35;81;2M. This happens when the terminal lags: over SSH, where a report can straddle two packets, or while pi’s event loop is busy re-rendering a long transcript (#384, #431). Reproduced on pi 1.2 and 1.4 alike. pi-tui’s input code is the same in both.

pi-modes listens on pi’s raw terminal input and drops such a pair, wherever the report was cut:

  • A head of ESC[< and part of its numbers is no keystroke. It is dropped, and so are the digits and semicolons after it, up to the report’s M or m. The guard watches for that tail for one second and at most sixteen characters.

  • A head cut sooner is also a keystroke: the lone ESC is the Escape key, and ESC[ is Alt+[ in some terminals. So the head passes, and what follows is only held: at most the rest of the introducer ([, <). The first may come up to a second after the head, since a slow render can sit between a head and its tail. Each one after it must come within 40 ms of the last, at machine speed. Once a digit follows, the report is certain and its tail is dropped as above.

  • Held characters that turn out to be typing are given back intact and in order. They come with the next character when that is text, or are pasted into the editor before a key that is not text, or once 40 ms pass with nothing.

Pins: test/mouse-tail.test.ts. It covers head and tail dropped through M/m at every cut point, as a property; typing after Escape or Alt+[ arriving intact and in order, as a property; whole reports and ordinary input passing; the time and length bounds; and one listener per interactive session, its give-back wired to the editor.

No extension can undo a lone ESC once pi has acted on it as Escape, and Escape aborts a running turn. That was the operator’s "spurious abort" (#483). The guard then swallowed the tail, so nothing showed in the editor. pi-modes therefore stops the split that causes it:

The lone-ESC patch (a temporary workaround, #487)

pi-tui emits a lone ESC as Escape when its timer expires. Node runs expired timers before it reads input that arrived in the meantime. So when a render blocks the event loop past the timer, the timer fires first, even if the rest of the report arrived a millisecond after the ESC. At extension load, pi-modes patches pi-tui’s input buffer: when that timer fires, it yields one event-loop step, so input that already arrived is read first, and only then emits the ESC. A real Escape keeps its timing; a report cut by a long render arrives whole. Nothing else in pi’s input handling changes.

This is a deliberate workaround on pi internals, to be removed once pi-tui ships the fix (#487 tracks it, and the upstream report):

  • Guarded. It is applied once per process, and only when pi-tui’s StdinBuffer has the methods and fields it was written for, checked one by one rather than by pi-tui’s version; otherwise it does nothing. The diagnostics stream (Diagnostics) records what happened: lone_escape.patch with applied, already, stale (another version of the patch is already on it), shape-changed or disabled.

  • Visible. Each report it rescues is recorded as lone_escape.rescued, with how long the ESC waited. If a split still happens, the guard above records mouse_tail.after_escape when a bare ESC proves to have been half a mouse report, so an abort nobody pressed Esc for shows its cause in /diag.

  • Switchable. GADHS_PI_TUI_PATCH=off in the shell that starts pi leaves pi-tui as it is.

  • Not covered by the patch: a real network gap longer than the timeout between two packets. The legacy keyboard encoding cannot tell that from an Esc press at the moment the ESC arrives. The next section covers that case.

Confirm before Escape acts (#495)

The diagnostics caught a split the patch cannot help with (2026-10-26). A lone ESC arrived; the patch yielded to pending input, and the rest of the report still had not arrived. It came about 125 ms later, across SSH from Windows Terminal. No timing inside pi can tell that from an Esc press when the ESC arrives, but the next few hundred milliseconds can.

So while the agent is streaming, the mouse-report guard holds a lone ESC instead of passing it:

  • If the rest of a mouse report follows, the ESC was never a keypress. Nothing reaches pi, and the guard records escape_confirm.spared.

  • If anything else follows, or nothing within 300 ms, the Escape was real. The guard replays it to pi exactly as the terminal sent it, on the input stream pi-tui reads, so whatever has focus handles it as Esc always does: the editor stops the run, and a selector, autocomplete or dialog closes. The guard records escape_confirm.escape. An extension cannot tell what has focus, which is why the guard replays rather than aborts. Only if nothing reads that stream does it stop the run itself.

  • Under the kitty keyboard protocol, Escape arrives as CSI 27 u, so a lone ESC is never the key. It is dropped (escape_confirm.dropped).

When the agent is idle, an ESC passes at once, as before.

The cost: while streaming, a real Esc acts up to 0.3 s later, plus pi-tui’s own 0.1 s escape wait over SSH. A report whose tail is more than 300 ms behind its head still acts as Escape. The guard still drops that tail, if it comes within a second of its head and even after the replay has returned, and records mouse_tail.after_escape, so /diag shows when it happens.

Pins: test/mouse-tail.test.ts covers each path on a fake clock: spared, timed out, a key, a quiet [, idle, kitty, a late tail, and the hold’s wiring. test/escape-confirm.integration.test.ts runs pi-tui’s real input buffer and real timers with the operator’s exact split, which reaches the editor as nothing, and a real Esc, which reaches it as the Escape key once, by the replay.

Pins: test/lone-escape.test.ts reproduces the bug with Node’s real event loop: the ESC and the rest of a report cross a loopback socket while the loop is blocked past the timer. Unpatched, the test sees Escape and then the tail as text (the control); patched, the whole report. It also covers a real Escape still emitted after the timeout, the once-only, shape and off guards, and the pinned pi-tui’s shape as a contract.

Edit this page · latest