From 2ff859c1cd18f5905e74d9b73c9baab33d37590c Mon Sep 17 00:00:00 2001 From: John Campion Jr Date: Mon, 9 Nov 2026 11:00:52 -0500 Subject: [PATCH] XTerm.NET + control: public shell/command state from OSC 133 --- README.md | 21 ++ src/XTerm.NET.Tests/ShellIntegrationTests.cs | 255 +++++++++++++++++++ src/XTerm.NET/Common/ShellState.cs | 49 ++++ src/XTerm.NET/Events/TerminalEvents.cs | 26 ++ src/XTerm.NET/InputHandler.Osc.cs | 1 + src/XTerm.NET/Terminal.cs | 54 ++++ 6 files changed, 406 insertions(+) create mode 100644 src/XTerm.NET/Common/ShellState.cs diff --git a/README.md b/README.md index 467d0066..036301ec 100644 --- a/README.md +++ b/README.md @@ -341,6 +341,27 @@ terminal.PointerShapeChanged += (sender, e) => }; ``` +**Shell state** (OSC 133 shell integration). `terminal.ShellState` says where the shell is: +`Unknown` (no marks yet, or a shell without integration), `Prompt` (after `133;A`, or after +`133;D` ends a command), `Input` (after `133;B`) or `Running` (after `133;C`). Each mark sets the +state outright, so a lost `D` is repaired by the next prompt's `A`; a full reset (RIS) returns it +to `Unknown`, and the alternate screen does not affect it. `ShellStateChanged` fires only when the +value changes, with the exit code of the `133;D` that ended a command: + +```csharp +// Ask before closing only while a command is running. +bool confirmClose = terminal.ShellState == ShellState.Running; + +terminal.ShellStateChanged += (sender, e) => +{ + if (e.OldState == ShellState.Running) + Console.WriteLine($"Command finished, exit code {e.ExitCode?.ToString() ?? "not reported"}"); +}; +``` + +`LastCommandExitCode` holds the last reported exit code; `ShellIntegrationState` and +`ShellIntegrationMarkReceived` give the raw marks. + **Window manipulation events** (used by some terminal applications): ```csharp diff --git a/src/XTerm.NET.Tests/ShellIntegrationTests.cs b/src/XTerm.NET.Tests/ShellIntegrationTests.cs index c9dc7d7f..1c41a114 100644 --- a/src/XTerm.NET.Tests/ShellIntegrationTests.cs +++ b/src/XTerm.NET.Tests/ShellIntegrationTests.cs @@ -177,6 +177,261 @@ public void Osc133_IgnoresEmptyPayload() Assert.Null(terminal.ShellIntegrationState); } + // ---- OSC 133 : derived shell state ------------------------------------------------------- + + private static List<(ShellState Old, ShellState New, int? Exit)> RecordShellStates(Terminal terminal) + { + var changes = new List<(ShellState, ShellState, int?)>(); + terminal.ShellStateChanged += (_, e) => changes.Add((e.OldState, e.NewState, e.ExitCode)); + return changes; + } + + [Fact] + public void ShellState_IsUnknownBeforeAnyMark() + { + var terminal = CreateTerminal(); + + Assert.Equal(ShellState.Unknown, terminal.ShellState); + } + + [Theory] + [InlineData("A", ShellState.Prompt)] + [InlineData("B", ShellState.Input)] + [InlineData("C", ShellState.Running)] + [InlineData("D;0", ShellState.Prompt)] + public void ShellState_FollowsEachMark(string mark, ShellState expected) + { + var terminal = CreateTerminal(); + var changes = RecordShellStates(terminal); + + terminal.Write($"\x1B]133;{mark}\x07"); + + Assert.Equal(expected, terminal.ShellState); + Assert.Equal(new[] { (ShellState.Unknown, expected, mark == "D;0" ? 0 : (int?)null) }, changes); + } + + [Fact] + public void ShellState_TracksAFullCycle_AndReportsTheExitCodeOnlyWhenTheCommandEnds() + { + var terminal = CreateTerminal(); + var changes = RecordShellStates(terminal); + + terminal.Write("\x1B]133;A\x07$ \x1B]133;B\x07"); + Assert.Equal(ShellState.Input, terminal.ShellState); + + terminal.Write("make\r\n\x1B]133;C\x07"); + Assert.Equal(ShellState.Running, terminal.ShellState); + + terminal.Write("error\r\n\x1B]133;D;2\x07"); + Assert.Equal(ShellState.Prompt, terminal.ShellState); + Assert.Equal(2, terminal.LastCommandExitCode); + + // The next prompt's A leaves the state where D put it, so it raises nothing. + terminal.Write("\x1B]133;A\x07"); + + Assert.Equal( + new (ShellState, ShellState, int?)[] + { + (ShellState.Unknown, ShellState.Prompt, null), + (ShellState.Prompt, ShellState.Input, null), + (ShellState.Input, ShellState.Running, null), + (ShellState.Running, ShellState.Prompt, 2), + }, + changes); + } + + [Fact] + public void ShellState_ReportsNoExitCode_ForABareD() + { + // cmd.exe always sends a bare D. Null must not read as success. + var terminal = CreateTerminal(); + terminal.Write("\x1B]133;C\x07"); + var changes = RecordShellStates(terminal); + + terminal.Write("\x1B]133;D\x07"); + + Assert.Equal(new[] { (ShellState.Running, ShellState.Prompt, (int?)null) }, changes); + } + + [Fact] + public void ShellState_RepeatedMarksRaiseNothing() + { + var terminal = CreateTerminal(); + terminal.Write("\x1B]133;C\x07"); + var changes = RecordShellStates(terminal); + + terminal.Write("\x1B]133;C\x07\x1B]133;C\x07"); + + Assert.Equal(ShellState.Running, terminal.ShellState); + Assert.Empty(changes); + } + + [Fact] + public void ShellState_FullReset_ReturnsToUnknown() + { + // RIS while a command runs is what `reset` itself produces: the state goes to Unknown, and + // the D that follows when `reset` exits brings it back to Prompt. + var terminal = CreateTerminal(); + terminal.Write("\x1B]133;C\x07"); + var changes = RecordShellStates(terminal); + + terminal.Write("\u001bc"); + Assert.Equal(ShellState.Unknown, terminal.ShellState); + + terminal.Write("\x1B]133;D;0\x07"); + Assert.Equal(ShellState.Prompt, terminal.ShellState); + + Assert.Equal( + new (ShellState, ShellState, int?)[] + { + (ShellState.Running, ShellState.Unknown, null), + (ShellState.Unknown, ShellState.Prompt, 0), + }, + changes); + } + + [Fact] + public void ShellState_FullResetWithNoState_RaisesNothing() + { + var terminal = CreateTerminal(); + var changes = RecordShellStates(terminal); + + terminal.Write("\u001bc"); + + Assert.Empty(changes); + } + + [Fact] + public void ResetShellState_ForgetsTheStateAndNothingElse() + { + // A host connecting the terminal to a new process: the old shell's state must go, its screen + // must not. + var terminal = CreateTerminal(); + terminal.Write("old output\r\n\x1B]133;C\x07"); + var changes = RecordShellStates(terminal); + + terminal.ResetShellState(); + + Assert.Equal(ShellState.Unknown, terminal.ShellState); + Assert.Equal(new[] { (ShellState.Running, ShellState.Unknown, (int?)null) }, changes); + Assert.StartsWith("old output", terminal.Buffer.Lines[0]!.TranslateToString(true)); + + // And the next shell's marks are heard from scratch, even a B the old shell had also sent last. + terminal.ResetShellState(); + terminal.Write("\x1B]133;B\x07"); + Assert.Equal(ShellState.Input, terminal.ShellState); + Assert.Equal(2, changes.Count); + } + + [Fact] + public void ShellState_SoftResetLeavesItAlone() + { + // DECSTR resets modes for the program that asked; it says nothing about the shell. + var terminal = CreateTerminal(); + terminal.Write("\x1B]133;C\x07"); + + terminal.Write("\x1B[!p"); + + Assert.Equal(ShellState.Running, terminal.ShellState); + } + + [Fact] + public void ShellState_RecoversFromAMissingD_AtTheNextPrompt() + { + // The shell crashed mid-command, or the command was killed before D: a new prompt's A is + // evidence enough that nothing is running any more. + var terminal = CreateTerminal(); + terminal.Write("\x1B]133;D;5\x07\x1B]133;A\x07\x1B]133;B\x07\x1B]133;C\x07"); + var changes = RecordShellStates(terminal); + + terminal.Write("\x1B]133;A\x07"); + + Assert.Equal(ShellState.Prompt, terminal.ShellState); + Assert.Equal(new[] { (ShellState.Running, ShellState.Prompt, (int?)null) }, changes); + // The last exit code is still the last one REPORTED; a missing D reports nothing. + Assert.Equal(5, terminal.LastCommandExitCode); + } + + [Fact] + public void ShellState_FollowsTheLatestMark_WhenMarksArriveOutOfOrder() + { + var terminal = CreateTerminal(); + + // C with no A or B before it: a shell whose integration starts mid-session. + terminal.Write("\x1B]133;C\x07"); + Assert.Equal(ShellState.Running, terminal.ShellState); + + // B with no A after a D: the prompt mark was dropped. + terminal.Write("\x1B]133;D\x07\x1B]133;B\x07"); + Assert.Equal(ShellState.Input, terminal.ShellState); + + // A while waiting for input: the prompt was redrawn (Ctrl+C, a resize). + terminal.Write("\x1B]133;A\x07"); + Assert.Equal(ShellState.Prompt, terminal.ShellState); + } + + [Fact] + public void ShellState_FollowsTheInnerShell_WhenShellsNest() + { + // `bash` run from bash: the outer shell's C, then the inner shell's own cycle, then the + // outer shell's D when the inner one exits. The terminal follows whoever spoke last. + var terminal = CreateTerminal(); + terminal.Write("\x1B]133;A\x07\x1B]133;B\x07\x1B]133;C\x07"); + + terminal.Write("\x1B]133;A\x07\x1B]133;B\x07"); + Assert.Equal(ShellState.Input, terminal.ShellState); + + terminal.Write("\x1B]133;C\x07"); + Assert.Equal(ShellState.Running, terminal.ShellState); + + terminal.Write("\x1B]133;D;0\x07\x1B]133;A\x07\x1B]133;B\x07"); + Assert.Equal(ShellState.Input, terminal.ShellState); + + // `exit` in the inner shell: the outer shell's D and its next prompt. + terminal.Write("\x1B]133;C\x07\x1B]133;D;0\x07\x1B]133;A\x07"); + Assert.Equal(ShellState.Prompt, terminal.ShellState); + } + + [Fact] + public void ShellState_IsUnchangedByTheAlternateScreen() + { + // vim takes the alternate screen inside a running command; neither switch is a shell mark. + var terminal = CreateTerminal(); + terminal.Write("\x1B]133;C\x07"); + var changes = RecordShellStates(terminal); + + terminal.Write("\x1B[?1049h"); + Assert.Equal(ShellState.Running, terminal.ShellState); + terminal.Write("\x1B[2J~\x1B[?1049l"); + + Assert.Equal(ShellState.Running, terminal.ShellState); + Assert.Empty(changes); + } + + [Fact] + public void ShellState_IgnoresUnknownMarks() + { + var terminal = CreateTerminal(); + terminal.Write("\x1B]133;C\x07"); + + terminal.Write("\x1B]133;Z\x07\x1B]133\x07"); + + Assert.Equal(ShellState.Running, terminal.ShellState); + } + + [Fact] + public void ShellState_IsCurrent_WhenTheMarkEventIsRaised() + { + // A handler of the raw mark event reading ShellState sees the state that mark produced. + var terminal = CreateTerminal(); + ShellState? seen = null; + terminal.ShellIntegrationMarkReceived += (_, _) => seen = terminal.ShellState; + + terminal.Write("\x1B]133;C\x07"); + + Assert.Equal(ShellState.Running, seen); + } + // ---- OSC 9 ; 9 : working directory ------------------------------------------------------- [Fact] diff --git a/src/XTerm.NET/Common/ShellState.cs b/src/XTerm.NET/Common/ShellState.cs new file mode 100644 index 00000000..236947ba --- /dev/null +++ b/src/XTerm.NET/Common/ShellState.cs @@ -0,0 +1,49 @@ +namespace XTerm.Common; + +/// +/// Where the shell is in its prompt/command cycle, as derived from its OSC 133 marks. +/// +/// +/// What reports, and the question a host asks before +/// closing a terminal: means a command owns the terminal and closing it would +/// kill that command; anything else means the shell itself has it. +/// The transitions, one per mark, with the latest mark always winning: +/// +/// 133;A (prompt start) - . +/// 133;B (input start) - . +/// 133;C (command start) - . +/// 133;D (command finished) - . The command is over and the shell has +/// the terminal back; what it does next is draw a prompt. Not , because the shell +/// has just told us exactly where it is. +/// RIS (ESC c) - . A full reset discards everything the terminal knew +/// about the session, and the shell has to say again. +/// +/// Because each mark sets the state outright, a lost 133;D - a shell that crashed and was +/// replaced, or a command killed before it could report - cannot leave the state stuck at +/// : the next prompt's 133;A puts it back. The same rule covers nesting: +/// a shell started from another shell sends its own marks, and the terminal follows whichever shell +/// spoke last. Switching to and from the alternate screen changes nothing. +/// +public enum ShellState +{ + /// + /// No mark since the terminal was created or last reset. Shell integration is configured in the + /// shell, so this is also the permanent state of a shell without it: "cannot say", never "idle". + /// + Unknown = 0, + + /// + /// The shell is drawing its prompt (after 133;A, or after 133;D ended a command). + /// + Prompt = 1, + + /// + /// The prompt is drawn and the shell is waiting for the user's command line (after 133;B). + /// + Input = 2, + + /// + /// A command is running and owns the terminal (after 133;C, until the next mark). + /// + Running = 3, +} diff --git a/src/XTerm.NET/Events/TerminalEvents.cs b/src/XTerm.NET/Events/TerminalEvents.cs index 3f761aae..26809247 100644 --- a/src/XTerm.NET/Events/TerminalEvents.cs +++ b/src/XTerm.NET/Events/TerminalEvents.cs @@ -672,4 +672,30 @@ public CursorStyleChangedEventArgs(CursorStyle style, bool blink) Blink = blink; } } + + /// + /// Shell state changed event - fired when takes a new value. + /// + public class ShellStateChangedEventArgs : EventArgs + { + public ShellStateChangedEventArgs(ShellState oldState, ShellState newState, int? exitCode) + { + OldState = oldState; + NewState = newState; + ExitCode = exitCode; + } + + /// The state before the change. + public ShellState OldState { get; } + + /// The state after the change, which now reports. + public ShellState NewState { get; } + + /// + /// The exit code the shell reported with the 133;D that caused this change, or null when + /// something else caused it or the shell sent a bare D. Null means "not reported", never + /// "succeeded". + /// + public int? ExitCode { get; } + } } diff --git a/src/XTerm.NET/InputHandler.Osc.cs b/src/XTerm.NET/InputHandler.Osc.cs index eef6d22b..48c5f64b 100644 --- a/src/XTerm.NET/InputHandler.Osc.cs +++ b/src/XTerm.NET/InputHandler.Osc.cs @@ -481,6 +481,7 @@ private void HandleShellIntegration(string data) line?.AddMark(new Buffer.LineMark(_buffer.X, mark, exitCode)); _terminal.ShellIntegrationState = mark; + _terminal.SetShellState(Terminal.ShellStateAfter(mark), exitCode); _terminal.RaiseShellIntegrationMark(mark, exitCode); } diff --git a/src/XTerm.NET/Terminal.cs b/src/XTerm.NET/Terminal.cs index 0eb76552..00a3f3d1 100644 --- a/src/XTerm.NET/Terminal.cs +++ b/src/XTerm.NET/Terminal.cs @@ -1448,6 +1448,9 @@ public void Reset() _altPointerShapes.Clear(); RaisePointerShapeChanged(shapeBefore); + // Whatever the shell last said no longer describes this session; it has to say again. + ResetShellState(); + // Reset cursor _buffer.SetCursor(0, 0); _buffer.ResetScrollRegion(); @@ -2538,6 +2541,7 @@ public void Dispose() DirectoryChanged = null; HyperlinkChanged = null; ShellIntegrationMarkReceived = null; + ShellStateChanged = null; PointerShapeChanged = null; ProgressChanged = null; NotificationReceived = null; @@ -2739,6 +2743,56 @@ private void AnnouncePaste(TerminalPaste paste) } internal void InvalidatePendingPaste() => _pendingPaste = null; + + // ---- Shell state (OSC 133) -------------------------------------------------------------- + + /// + /// Where the shell is in its prompt/command cycle, derived from its OSC 133 marks. + /// + /// + /// is the one a host acts on: a command owns the terminal, so + /// closing it should ask first. is what a shell without + /// integration reports forever, and means "cannot say". The transitions are documented on + /// . The raw last mark is . + /// + public ShellState ShellState { get; private set; } + + /// + /// Fired when changes; repeating a mark that leaves it where it was + /// fires nothing. Raised synchronously on the thread calling . + /// + public event EventHandler? ShellStateChanged; + + /// + /// Returns to without touching anything + /// else: the screen, the scrollback and the marks anchored in it all stay. + /// + /// + /// For a host that connects this terminal to a different process. The state describes the shell + /// that sent the last mark, and a new process that never sends one - a shell without integration - + /// would otherwise inherit it for good: idle from the old shell's B, or running from its C. Raises + /// when the state was known. A full reset (RIS) does this too. + /// + public void ResetShellState() => SetShellState(ShellState.Unknown, null); + + internal void SetShellState(ShellState state, int? exitCode) + { + var old = ShellState; + if (old == state) + return; + + ShellState = state; + ShellStateChanged?.Invoke(this, new TerminalEvents.ShellStateChangedEventArgs(old, state, exitCode)); + } + + // Each mark sets the state outright rather than stepping from the current one, which is what + // keeps a lost D or an out-of-order mark from wedging it: the next A is always a prompt. + internal static ShellState ShellStateAfter(ShellIntegrationMark mark) => mark switch + { + ShellIntegrationMark.CommandStart => ShellState.Input, + ShellIntegrationMark.CommandExecuted => ShellState.Running, + _ => ShellState.Prompt, + }; } ///