Terminal experience
kftui is the terminal application for managing Kubernetes port forwards. It accepts saved or imported configuration, can run as an interactive terminal user interface (TUI), and can keep forwards alive for scripts or other commands. It uses the same shared configuration and forwarding domain as the wider kftray product while giving terminal users a separate startup, input, logging, update, and install experience. See Terminal application workflows for the detailed command and screen flows.
Application boundary
The terminal application turns one command invocation into one of two user experiences: a screen-based session or a headless run. Both modes prepare configuration and forwarding through the same startup path, then differ in how they show status and how they wait for shutdown.
flowchart TD
A[Start kftui] --> B[Parse and validate CLI]
B --> C[Choose file or memory configuration]
C --> D[Import or discover configuration]
D --> E{Execution mode}
E -->|Interactive| F[Open TUI]
E -->|Headless| G[Start forwards or save configuration]
F --> H[Read input and refresh state]
G --> I[Keep forwards, watch, or run command]
H --> J[Stop and clean up]
I --> J
The interactive path is the normal terminal experience. The headless path supports automation, command wrappers, configuration import, and discovery without drawing a screen. --watch extends discovery in either path by looking for new annotated services during the run.
Headless shutdown treats forwarding cleanup as part of the run result. It stops discovered forwards and the optional network monitor before it exits, keeps stop work alive when a wait budget expires, and reports unfinished cleanup so a script can detect an incomplete run.
References: crates/…/README.md• L1-11 crates/…/main.rs• L25-76 crates/…/handler.rs• L33-45 crates/…/args.rs• L159-205 crates/…/runner.rs• L203-233 crates/…/runner.rs• L639-760
CLI startup
The CLI startup path prepares the runtime before it starts user work. It initializes async support, shared security and path services, output rules, logging, and the command handler. The handler then validates the argument contract, prepares the selected configuration store, imports any source, and chooses the final execution mode.
Configuration sources are exclusive. A run can load a local file, inline JSON, piped JSON, a GitHub repository path, or Kubernetes service annotations. Without a source, kftui uses saved configurations; with a source and without --save, it uses an in-memory store so the imported data does not change the saved set.
| Startup choice | User goal | Result |
|---|---|---|
| Interactive run | Manage saved or imported forwards in a screen | Opens the TUI after import and optional auto-start |
--non-interactive | Run an action without a screen | Saves or starts forwards, then exits or waits for a signal |
--auto-start | Start selected configurations | Starts matching forwards before the chosen mode begins |
Command after -- | Use forwards for one child command | Starts forwards, runs the command, then stops them and returns its exit code |
--watch | Track new annotated services | Repeats discovery while the run remains active |
--non-interactive is also implied when a command follows --. Validation keeps related options together, such as requiring --auto-discover for discovery settings and --auto-start for a child command. These checks prevent a partial startup from being mistaken for a valid run.
When kftui runs a child command, the command owns its normal exit result while kftui remains responsible for forwarding teardown. A missing command maps to the shell-style failure code 127; another spawn failure maps to 126. A successful child command still produces a failed kftui run if forwarding cleanup does not finish.
References: crates/…/main.rs• L45-76 crates/…/args.rs• L25-157 crates/…/args.rs• L159-337 crates/…/handler.rs• L22-159 crates/…/config.rs• L22-38 crates/…/runner.rs• L260-379 crates/…/test_cli_runner.rs• L20-41 crates/…/test_cli_runner.rs• L215-279
Interactive TUI
The TUI gives a live view of stopped and running configurations and lets the user manage them from one terminal screen. It enters raw terminal mode and an alternate screen, refreshes shared configuration and runtime state on a short cycle, draws the current view, and sends keyboard events to the active screen or popup.
The main screen connects navigation to forwarding actions. The application can show tables, search and grouping views, configuration details, settings, help, import and export screens, HTTP log views, consent prompts, update prompts, and error messages. These are views over one running session rather than separate processes.
sequenceDiagram
participant T as Terminal
participant L as TUI loop
participant D as Shared data
participant F as Forwarding service
T->>L: Key or resize event
L->>D: Read configurations and states
L->>F: Start, stop, or change a forward
F-->>D: Update runtime state and errors
L-->>T: Draw tables, details, or popup
The TUI owns the session state in App. It keeps the selected rows, active view, filters, pending work, errors, logs, consent state, update state, and quit request together so input and rendering see the same session picture. A normal exit and Ctrl+C use the same shutdown path: the terminal is restored first, then discovery, monitors, and forwarding work are stopped and reconciled.
Forwarding actions run as background work so the screen can continue to accept input. Each operation has a busy state and a stall warning rather than an early forced abort. During shutdown the app cancels new work and drains existing tasks within bounded waits; work that cannot safely stop is detached and reported so later cleanup can retry it. Unshown errors remain available after the screen closes instead of disappearing with the alternate screen.
The input state machine routes each terminal event to the active view or popup. Ctrl+C sets the shared quit request from any popup, while resize events update the visible row budget without consuming the next key event. Normal views support navigation, search, selection, forwarding actions, settings, and logs; modal views consume keys until they close.
References: crates/…/app.rs• L47-147 crates/…/app.rs• L166-239 crates/…/mod.rs• L1278-1433 crates/…/mod.rs• L1941-2045 crates/…/mod.rs• L2047-2135 crates/…/mod.rs• L564-703 crates/…/test_input.rs• L98-141
Application state
App is the TUI session model. It combines user view state with live forwarding state so the interface can show what is stopped, running, being processed, or waiting for user action. It also carries the resources needed to finish work when the screen closes.
The state has four broad roles:
- View state: selected tables, search, filters, grouping, details, menus, and scroll positions.
- Operation state: configurations, forwarding tasks, cancellation, retries, progress, and error reports.
- Supporting state: settings, HTTP log views, active pods, telemetry consent, and logger access.
- Session state: update prompts, restart notices, pending errors, retry hints, and the shared quit flag.
The event loop reloads configuration and runtime state before each draw. Actions change the shared domain through the forwarding and configuration services, then later refreshes bring those results back into the screen. This keeps the TUI responsive while long start, stop, discovery, or log operations run as async work. The refresh also moves completed task errors into an error popup when it is safe to interrupt the current view and keeps them queued during another modal action.
Error popups are part of the user-facing recovery path. They group failures, allow the user to scroll through a batch, preserve the scroll limit used by the renderer, and always keep a close action visible on small terminals. A busy-port failure can also offer a retry on the free port named by the failure.
References: crates/…/mod.rs• L345-451 crates/…/mod.rs• L459-585 crates/…/mod.rs• L587-703 crates/…/mod.rs• L963-1125 crates/…/popup.rs• L630-835 crates/…/test_input.rs• L302-357 crates/…/test_ui_popup.rs• L142-259
Standard input
Standard input has two roles that must not conflict: it can carry JSON configuration, or it can carry keyboard input for the TUI. The --stdin source reads only from a pipe or redirected input and rejects a terminal-connected stdin, which prevents the application from consuming the keyboard as configuration data.
After a piped import, an interactive macOS run restores stdin to the controlling terminal before it opens the TUI. This platform-specific step works around the terminal event behavior that can prevent keyboard input after stdin has been consumed. Headless runs do not need this handoff because they do not read interactive key events.
References: crates/…/stdin.rs• L1-13 crates/…/stdin.rs• L98-108 crates/…/config.rs• L135-149 crates/…/config.rs• L214-220 crates/…/handler.rs• L119-132 crates/…/test_cli_runner.rs• L267-279
Logging and output
Logging has two destinations that match the user mode. Interactive runs place logs in the TUI logger so messages do not overwrite the screen. --logs-to-file sends logs to the application log file instead, which is useful when the terminal is reserved for another output stream or when a run needs a persistent record.
Messages printed outside the TUI use the selected message level. Status normally goes to stdout, while warnings and errors go to stderr. When kftui runs a child command after --, all kftui messages go to stderr so the command can use stdout for its own pipe or file. The logger state tells the TUI whether it should move in-screen log events or leave them to the file logger.
References: crates/…/main.rs• L57-76 crates/…/config.rs• L3-40 crates/…/initializer.rs• L8-53 crates/…/state.rs• L5-26 crates/…/output.rs• L1-39
Update behavior
Release updates are an optional part of the interactive session. In production builds, kftui checks GitHub releases in the background at TUI startup unless --no-update-check is set. The check compares the running version with the latest release and also confirms that a binary for the current platform exists.
When a newer release is available, the TUI shows a confirmation prompt. If the user accepts, kftui downloads the matching release asset, checks that it is a gzip archive, replaces the running executable, and shows a restart notice. Development builds do not perform the release check and report that updates are disabled if the update action is selected.
References: crates/…/app.rs• L68-75 crates/…/updater.rs• L15-79 crates/…/updater.rs• L81-172 crates/…/mod.rs• L3241-3303 crates/…/mod.rs• L3315-3338 crates/…/popup.rs• L428-628
Installation utilities
The installation utilities fetch the latest kftui release and place the executable in a user-local binary directory. The Unix script supports macOS, Linux, and WSL, selects a supported architecture, downloads the matching release, and adds the install directory to shell startup files when needed. The PowerShell script performs the same user-local install for Windows and updates the user PATH.
Both utilities verify that the release can be fetched and that the installed executable is available. They are separate from in-app update behavior: installation finds the latest release for a new setup, while the TUI update flow replaces an existing running executable.
References: hacks/kftui_installer.sh• L24-47 hacks/kftui_installer.sh• L68-98 hacks/kftui_installer.sh• L100-173 hacks/kftui_installer.ps1• L20-52 hacks/kftui_installer.ps1• L54-69
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the CLI validation rules aligned with the source-selection and execution branches in
CliHandlerandPortForwardRunner. - Preserve the stdout and stderr contract for child-command runs so command output stays safe to pipe.
- Keep every TUI exit path behind the terminal-restore and forwarding-cleanup sequence.
- Keep forwarding task cancellation, drain budgets, detached task tracking, and later cleanup reconciliation consistent.
- Preserve the error-popup contract: queued failures must remain available, long batches must scroll, and small terminals must show a close action.
- When adding a platform release asset, update both the updater asset mapping and the matching installer URL rules.
- When changing stdin import behavior, check the macOS terminal handoff and the interactive versus headless split together.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
A child command is used without --auto-start | Startup rejects the run instead of running a command with no forwards | CLI validation requires both options |
| A child command cannot start | kftui returns a shell-style failure code and still performs forwarding cleanup | Command startup maps missing programs to 127 and other spawn errors to 126 |
| A piped JSON source is used with a terminal-connected stdin | Configuration import fails rather than treating keyboard input as JSON | read_stdin_content requires non-TTY input |
| A TUI update asset is missing for the current platform | The update check fails and no update prompt is shown | Release checking verifies the platform asset |
| A forwarding task stalls during an interactive run | The row stays busy and the user receives a warning instead of an unsafe forced abort | The watchdog warns once and lets backend rollback complete |
| Shutdown exceeds its cleanup budget | Some work remains running and the run reports incomplete cleanup | Stops are spawned before draining, unfinished ids are tracked, and reconciliation retries owed work |
| A long error batch exceeds the popup area | Later failures become unreadable or the user loses the way to close the popup | The popup scrolls, clamps offsets, and reserves a close hint |
Key files
| File | Why to read it |
|---|---|
| crates/…/main.rs | Shows process startup, runtime setup, logger choice, and handler handoff. |
| crates/…/args.rs | Defines the user-facing command contract and mode rules. |
| crates/…/handler.rs | Connects validation, import, database mode, TUI startup, and headless execution. |
| crates/…/runner.rs | Shows how headless runs start, supervise, run child commands, and stop forwards. |
| crates/…/app.rs | Shows the TUI lifecycle, refresh loop, update check, and shutdown boundary. |
| crates/…/mod.rs | Defines session state, forwarding task lifetime, popup recovery, and terminal event handling. |
| crates/…/popup.rs | Shows how the TUI presents errors, settings, updates, and other modal actions. |
| crates/…/stdin.rs | Defines piped JSON input and the macOS interactive stdin handoff. |
| crates/…/initializer.rs | Shows the in-screen and file logging destinations. |
| crates/…/updater.rs | Defines release checks and in-app replacement behavior. |
| hacks/kftui_installer.sh | Shows the Unix and WSL install path. |
hacks/kftui_installer.ps1 | Shows the Windows install path. |