Backends and terminal
kite.New(b, opts...) takes a backend.Backend and returns an engine. The backend receives rendered frames and supplies raw terminal input. Use backend/uv for a real terminal; use backend/mock or the test environment for deterministic headless interaction.
b, err := uv.New()if err != nil { return err}
app := kite.New(b, kite.WithMouseMode(kite.MouseModeTrack), kite.WithClipboard(clipboard.New()),)Options apply in order. Pass kite.WithOptions first when using a kite.Options struct as a baseline (for example, to set MacroTaskBudget or MacroTaskDuration).
Option (kite) |
Purpose |
|---|---|
WithOptions(opts) |
Replace the baseline kite.Options struct without changing mouse mode |
WithMouseMode(mode) |
Select mouse reporting (MouseModeOff, MouseModeClick, MouseModeDrag, MouseModeTrack) |
WithClipboard(cb) |
Override the default OSC 52 clipboard provider (e.g. clipboard.New()) |
WithInline(enabled) |
Render inline at the current cursor position instead of the alternate screen |
WithProfiler(enabled) |
Enable phase profiling and tracing at startup |
WithClock(clk) |
Supply a custom kite.Clock (defaults to kite.RealClock()) |
WithWorkers(n) |
Set the background worker pool size (defaults to engine.DefaultWorkers) |
WithShutdownTimeout(d) |
Bound how long Stop waits for pending background jobs (defaults to 5s) |
Custom I/O & SSH Embedding
Section titled “Custom I/O & SSH Embedding”Use one uv.Backend per session. WithInput accepts an io.Reader and WithOutput an io.Writer; omitted streams use standard input and output. WithEnviron replaces, rather than extends, the process environment. Pass an explicit slice (even an empty one) so one session cannot inherit or consume another terminal’s settings. Build it from trusted settings and the terminal hints your server accepts, not arbitrary client variables. For a remote color terminal without a local file descriptor, CLICOLOR_FORCE=1 enables color detection from those hints.
WithSize sets the initial width and height in cells for non-TTY streams (or when a local TTY size cannot be queried); on a local TTY the backend queries the TTY first, falling back to WithSize and then 80×24. Only NotifyResize overrides a local TTY’s size. Forward SSH window changes to NotifyResize; it ignores non-positive dimensions and can coalesce rapid updates. It is safe before startup or after shutdown, so the resize goroutine needs no special handshake.
For example, in a Wish handler using github.com/charmbracelet/ssh:
func runSession(s ssh.Session) error { pty, windows, ok := s.Pty() if !ok { return fmt.Errorf("this application requires a PTY") }
b, err := uv.New( uv.WithInput(s), uv.WithOutput(s), uv.WithEnviron([]string{"TERM=" + pty.Term, "CLICOLOR_FORCE=1"}), uv.WithSize(pty.Window.Width, pty.Window.Height), ) if err != nil { return err }
ctx, cancel := context.WithCancel(s.Context()) defer cancel() go func() { for { select { case <-ctx.Done(): return case win, ok := <-windows: if !ok { return } b.NotifyResize(win.Width, win.Height) } } }()
app := kite.New(b) return app.Run(ctx)}For a pipe, pass its read end to WithInput. If a non-file reader can block indefinitely, supply an io.ReadCloser whose Close interrupts Read, or arrange for the read to finish before shutdown. Restore may close the input to unblock it; if input and output are the same SSH channel, this also ends the session. The backend does not separately close the output writer.
Services on the document
Section titled “Services on the document”Use doc.Terminal() rather than writing terminal escapes into standard output. Do not rely on host integration as the only way to show an important message, as terminals vary in which protocols they support.
Method (terminal.Terminal) |
Service |
|---|---|
Cursor() |
Per-frame hardware cursor control (SetPosition, SetShape, Hide) |
Clipboard() |
Asynchronous plain-text and MIME-typed clipboard (ReadText, WriteText, ListFormats, Read, Write) |
Window() |
Host color scheme (ColorScheme()), repaint requests (RequestFrame()), and one-shot frame callbacks (RequestAnimationFrame()) |
Scheduler() |
Worker pool and main-thread queues (RunBackground, Spawn, QueueMicrotask, QueueMacrotask) |
SetTitle(title) |
Change the terminal window title (no-op if unsupported) |
Bell() |
Ring the terminal bell (no-op if unsupported) |
SetProgressBar(state, percentage) |
Update the terminal’s native progress bar (ProgressBarHide, ProgressBarNormal, ProgressBarError, ProgressBarIndeterminate, ProgressBarPaused) |
SetProgramStatus(status) |
Report structured status via OSC 7501 (*terminal.ProgramStatus; pass nil to clear) |
SetProgramResume(resume) |
Register a restart command via OSC 7577 (*terminal.ProgramResume; pass nil to clear) |
ExecProcess(ctx, cmd) |
Suspend the backend, run an interactive subprocess, and resume rendering |
OnClose(fn) / IsClosed() |
Register a host shutdown callback and query shutdown state |
Running an interactive command
Section titled “Running an interactive command”ExecProcess lends the terminal to a child and waits for it to exit. Call it from an event handler or a background goroutine. For example, to edit a file with an editor executable selected by the user:
func edit(ctx context.Context, term terminal.Terminal, path string) error { editor := os.Getenv("EDITOR") if editor == "" { editor = "vi" } return term.ExecProcess(ctx, exec.Command(editor, path))}Kite restores cooked input and the normal screen for the child, then resumes the UI and repaints it even if the command fails. Unset command streams inherit the session streams; explicit streams are preserved. Cancel ctx to terminate the child. Concurrent calls return engine.ErrExecBusy. The backend must implement the optional backend.Suspender interface (Suspend and Resume); otherwise the call returns engine.ErrExecUnsupported, as on the browser backend. In Kitex, obtain the terminal using the getter returned by UseTerminal().
Shutdown
Section titled “Shutdown”Pass a cancellable context to app.Run(ctx) so the engine can stop and restore the terminal. A frame-loop panic is logged, the terminal is restored, and the panic propagates: restoration is not error suppression. Avoid exiting the process directly from an event callback, which bypasses deferred cleanup.