package ui import ( "context" "encoding/json" "errors" "fmt" "hash/fnv" "os" "os/exec" "path/filepath" "slices" "sort" "strings" "time" "charm.land/bubbles/v2/key" tea "charm.land/bubbletea/v2" "charm.land/lipgloss/v2" "github.com/charmbracelet/log" "github.com/charmbracelet/x/ansi" "github.com/charmbracelet/x/editor" "github.com/spf13/viper" "github.com/mark3labs/kit/internal/app" "github.com/mark3labs/kit/internal/auth" "github.com/mark3labs/kit/internal/core" "github.com/mark3labs/kit/internal/message" "github.com/mark3labs/kit/internal/models" "github.com/mark3labs/kit/internal/prompts" "github.com/mark3labs/kit/internal/ui/clipboard" "github.com/mark3labs/kit/internal/ui/commands" uicore "github.com/mark3labs/kit/internal/ui/core" "github.com/mark3labs/kit/internal/ui/fileutil" "github.com/mark3labs/kit/internal/ui/imagepreview" "github.com/mark3labs/kit/internal/ui/prefs" "github.com/mark3labs/kit/internal/ui/style" "github.com/mark3labs/kit/internal/ui/termgfx" kit "github.com/mark3labs/kit/pkg/kit" ) // appState represents the current state of the parent TUI model. type appState int const ( // stateInput is the default state: input is focused and the user is waiting // to type. The agent is not running. stateInput appState = iota // stateWorking means the agent is running. The stream component is active. // The input component remains visible and editable for queueing messages. stateWorking // stateTreeSelector means the /tree viewer is active. stateTreeSelector // statePrompt means an extension-triggered interactive prompt is active. // The prompt overlay takes full focus until the user completes or cancels. statePrompt // stateOverlay means an extension-triggered modal overlay dialog is active. // The overlay takes over the full view until the user completes or cancels. stateOverlay // stateModelSelector means the /model selector overlay is active. stateModelSelector // stateThinkingLevelSelector means the /thinking selector overlay is active. stateThinkingLevelSelector // stateModelModeSelector means the /mode selector overlay is active. stateModelModeSelector // stateThemeSelector means the /theme selector overlay is active. stateThemeSelector // stateProviderConnect means the /connect provider/key dialog is active. stateProviderConnect // stateSessionSelector means the /resume session picker is active. stateSessionSelector // stateMessageNav means scrollback message navigation is active. The // user moves a selection between messages with up/down (or j/k) and // opens the selected message in a scrollable inspector with Enter. // The composer keeps its text but does not receive keys. stateMessageNav ) // AppController is the interface the parent TUI model uses to interact with the // app layer. It is satisfied by *app.App once that is created (TAS-4). // Using an interface here keeps model.go compilable before app.App exists, and // makes the parent model easily testable with a mock. type AppController interface { // Run queues or immediately starts a new agent step with the given prompt. // Returns the current queue depth: 0 means the prompt started immediately // (or the app is closed), >0 means it was queued. The caller must update // UI state (e.g. queueCount) based on the return value — Run does NOT // send events to the program to avoid deadlocking when called from // within Update(). Run(prompt string) int // CancelCurrentStep cancels any in-progress agent step. CancelCurrentStep() // QueueLength returns the number of prompts currently waiting in the queue. QueueLength() int // ClearQueue discards all queued prompts. The caller must update UI state // (e.g. queueCount) — ClearQueue does NOT send events to the program to // avoid deadlocking when called from within Update(). ClearQueue() // ClearMessages clears the conversation history. ClearMessages() // ReloadMessagesFromTree clears the in-memory message store and reloads // it from the tree session's current branch. Unlike ClearMessages, this // does NOT reset the tree session's leaf pointer. Used after Branch() to // sync the store with the new branch position. ReloadMessagesFromTree() // CompactConversation summarises older messages to free context space. // Runs asynchronously; results are delivered via CompactCompleteEvent or // CompactErrorEvent sent through the registered tea.Program. Returns an // error synchronously if compaction cannot be started (e.g. agent is busy). // customInstructions is optional text appended to the summary prompt. CompactConversation(customInstructions string) error // SessionSnapshot returns a value snapshot of the active tree session's // metadata (id, name, file path, counts, current leaf). ok is false when // no tree session is active. Callers re-read it whenever they need // current values rather than caching it. SessionSnapshot() (app.SessionSnapshot, bool) // SessionTree returns the session's entry tree projected into value // nodes, or nil when no tree session is active. Used by /tree and /fork. SessionTree() []app.TreeNodeView // SessionHistory returns the conversation messages on the session's // current branch, oldest first. Used to replay the transcript after // resuming or forking a session. SessionHistory() []message.Message // SetSessionName sets the session's display name. Used by /name. SetSessionName(name string) error // NewSession replaces the active session with a brand new one created in // cwd, closing the old one. Used by /new. NewSession(cwd string) error // ForkSession creates a new session in cwd holding the history up to // targetID and switches to it. Used by /fork and tree-node selection. ForkSession(cwd, targetID string) error // ListSessions returns summaries of the sessions recorded for cwd, // newest first. Used by the session picker. ListSessions(cwd string) ([]app.SessionSummary, error) // ListAllSessions returns summaries of every session across all working // directories, newest first. Used by the session picker's "All" scope. ListAllSessions() ([]app.SessionSummary, error) // DeleteSession removes a session file from disk. Used by the session // picker's delete flow. DeleteSession(path string) error // ExportSession copies the active session's file to dstPath, deriving a // name when dstPath is empty, and reports the path written and byte // count. Used by /export. ExportSession(dstPath string) (string, int, error) // WriteShareableSession writes a shareable copy of the active session // (with a system-prompt entry spliced in) to a temporary file and returns // its path. The caller must remove the file. Used by /share. WriteShareableSession(systemPrompt, fallbackModelID string) (string, error) // SendUIMessage re-injects a UI-internal message into the program's Update // loop asynchronously. Safe to call from any goroutine. Used by extension // command goroutines (and other async UI work) to deliver results back to // the TUI without going through tea.Cmd (which can stall when the goroutine // blocks on interactive prompts). The message is opaque to the app layer; // it is not an app Event and is only understood by the UI's own Update. SendUIMessage(tea.Msg) // AddContextMessage adds a user-role message to the conversation history // without triggering an LLM response. Used by the ! shell command prefix // to inject command output into context so the LLM can reference it in // subsequent turns. AddContextMessage(text string) // RunWithFiles queues a multimodal prompt (text + images) for execution. // Behaves like Run but includes file parts (e.g. clipboard images) // alongside the text. Returns the current queue depth (0 = started // immediately, >0 = queued). RunWithFiles(prompt string, files []kit.LLMFilePart) int // Steer injects a steering message into the currently running agent // turn. If the agent is busy, the message is delivered between steps // (after current tool finishes, before next LLM call). If idle, the // message starts executing immediately. Returns 0 if started // immediately, >0 if injected/pending. Steer(prompt string) int // SteerWithFiles injects a steering message with optional file // attachments (e.g. pasted images) into the currently running agent // turn. Behaves like Steer but includes file parts alongside the text. SteerWithFiles(prompt string, files []kit.LLMFilePart) int // PopLastUserMessage truncates the tree session at the parent of the // most recent user message on the current branch, syncs the in-memory // message store, and returns that user prompt (plus any image file // parts) so the caller can resubmit it. Used by /retry to recover from // provider errors (overloaded, timeout) without duplicating the user // message in context. Returns an error if the agent is busy, no tree // session is active, or no user message exists on the current branch. PopLastUserMessage() (string, []kit.LLMFilePart, error) // RunningSubagents returns the in-process subagents that are running // now, oldest first. Used by /kill-subagent. RunningSubagents() []kit.RunningSubagent // KillSubagent stops the running subagent with the given ID. Returns // false when no such subagent is running. Used by /kill-subagent. KillSubagent(id string) bool } // SkillItem holds display metadata about a loaded skill for the startup // [Skills] section. Built by the CLI layer from the SDK's []*kit.Skill. type SkillItem struct { Name string // Skill name (e.g. "btca-cli"). Path string // Absolute path to the skill file. Source string // "project" or "user" (global). Description string // Short summary used in autocomplete and help. } // ExtensionItem holds display metadata about a loaded extension for the // startup [Extensions] section. Built by the CLI layer from the SDK's // []kit.ExtensionInfo. type ExtensionItem struct { Name string // Extension display name (filename without .go extension). Path string // Absolute path to the extension's .go file. Source string // "project" or "user" (global). } // MCPPromptInfo describes an MCP prompt for display in the TUI (autocomplete, // help). This is a pure UI type — it carries no MCP client dependencies. type MCPPromptInfo struct { Name string // Prompt name on the MCP server. Description string // Human-readable description. Arguments []MCPPromptArgInfo // Expected arguments. ServerName string // Owning MCP server name. } // MCPPromptArgInfo describes an argument for an MCP prompt. type MCPPromptArgInfo struct { Name string Description string Required bool } // MCPPromptExpandResult is the result of lazily expanding an MCP prompt. type MCPPromptExpandResult struct { Messages []MCPPromptMessageInfo } // MCPPromptMessageInfo is a single message from an expanded MCP prompt. type MCPPromptMessageInfo struct { Role string // "user" or "assistant" Content string FileParts []kit.LLMFilePart } // ToolRendererData holds extension-provided rendering functions for a specific // tool. The UI layer uses this to override the default tool header/body // rendering without depending on the extensions package directly. type ToolRendererData struct { // DisplayName, if non-empty, replaces the auto-capitalized tool name // in the header line. DisplayName string // BorderColor, if non-empty, overrides the default success/error border // color. Hex string (e.g. "#89b4fa"). BorderColor string // Background, if non-empty, sets a background color for the tool block. // Hex string (e.g. "#1e1e2e"). Background string // BodyMarkdown, when true, renders the RenderBody output as markdown // via glamour. Ignored when RenderBody is nil or returns empty. BodyMarkdown bool // MaxBodyLines, when greater than zero, replaces the transcript's line // limits for the body that Kit renders itself, builtin or plain. The // message inspector still shows the full result. MaxBodyLines int // RenderHeader, if non-nil, replaces the default parameter formatting // in the tool header line. Receives the JSON-encoded arguments and max // width. Return a short summary string, or empty to fall back to default. RenderHeader func(toolArgs string, width int) string // RenderBody, if non-nil, replaces the default tool result body. Receives // the result text, error flag, and available width. Return the full styled // body content, or empty to fall back to builtin/default renderer. RenderBody func(toolResult string, isError bool, width int) string } // noopCmd is a sentinel tea.Cmd returned by handlers that have consumed an // event but produce no side-effects. It returns a nil Msg which BubbleTea // discards, but its non-nil value lets callers distinguish "handled" from // "not handled" (nil tea.Cmd). var noopCmd tea.Cmd = func() tea.Msg { return nil } // Package-level lipgloss styles that are invariant across frames (only depend // on theme colors, which are updated via SetTheme). Defined at package level // to avoid allocating new lipgloss.Style structs on every render call. // // Note: theme-sensitive styles (those using theme.Warning, theme.Muted, etc.) // are rebuilt on theme change via ApplyTheme. The cancel warning style // intentionally reads the theme at render time because themes can change at // runtime; only truly static styles belong here. var styleMarginBottom1 = lipgloss.NewStyle().MarginBottom(1) // --------------------------------------------------------------------------- // Editor interceptor types (UI-layer, decoupled from extensions package) // --------------------------------------------------------------------------- // ShortcutInfo describes one extension-registered keyboard shortcut for the // /shortcuts listing. Mirrors extensions.ShortcutEntry for package decoupling. type ShortcutInfo struct { // Key is the normalized binding, e.g. "ctrl+p". Key string // Description explains what the shortcut does. Description string // Source is the file name of the extension that registered it. Source string } // EditorKeyActionType defines the outcome of an editor key interception. // Mirrors extensions.EditorKeyActionType for package decoupling. type EditorKeyActionType string const ( // EditorKeyPassthrough lets the built-in editor handle the key normally. EditorKeyPassthrough EditorKeyActionType = "passthrough" // EditorKeyConsumed means the extension handled the key. EditorKeyConsumed EditorKeyActionType = "consumed" // EditorKeyRemap transforms the key into a different key. EditorKeyRemap EditorKeyActionType = "remap" // EditorKeySubmit forces immediate text submission. EditorKeySubmit EditorKeyActionType = "submit" ) // EditorKeyAction is the UI-layer equivalent of extensions.EditorKeyAction. type EditorKeyAction struct { // Type determines the action taken. Type EditorKeyActionType // RemappedKey is the target key name for EditorKeyRemap. RemappedKey string // SubmitText is the text to submit for EditorKeySubmit. SubmitText string } // EditorInterceptor is the UI-layer representation of an extension editor // interceptor. It decouples the UI package from the extensions package. // The CLI layer converts the extension EditorConfig to this type. type EditorInterceptor struct { // HandleKey intercepts key presses before the built-in editor. HandleKey func(key string, currentText string) EditorKeyAction // Render wraps the built-in editor's rendered output. Render func(width int, defaultContent string) string } // widgetRenderCache holds the last output of an animated widget's Render // callback, so the interpreter is re-entered at the widget's requested rate // rather than on every frame the shared clock ticks. type widgetRenderCache struct { content string width int height int beat int } // WidgetData is the UI-layer representation of an extension widget. It // decouples the UI package from the extensions package. The CLI layer // converts extension WidgetConfig values to WidgetData for rendering. type WidgetData struct { // ID uniquely identifies the widget. Used to key the animation render // cache; empty for header/footer, which get synthetic keys. ID string // Text is the content to display. Ignored when Render is non-nil. Text string // Markdown, when true, renders Text as styled markdown. Markdown bool // Render, if non-nil, produces the widget body per frame from the // content width. Its output is used verbatim. Render func(width int) string // FillHeight shares the transcript rows with other above/below fill widgets. FillHeight bool // RenderSized receives the content width and assigned fill height. RenderSized func(width, height int) string // RefreshHz, when > 0, asks the shared animation clock to keep running // so the widget repaints continuously. It also bounds how often Render // is actually invoked. Zero means a static widget. RefreshHz int // BorderColor is a hex color (e.g. "#a6e3a1") for the left border. // Empty uses the theme's default accent color. BorderColor string // NoBorder disables the left border entirely. NoBorder bool } // StatusBarEntryData represents a keyed extension entry in the TUI status bar. // Multiple entries from different extensions coexist, ordered by Priority // (lower values render further left). type StatusBarEntryData struct { Key string // unique identifier (e.g. "myext:git-branch") Text string // rendered content shown in the status bar Priority int // lower = further left; built-in entries use 100-110 } // UIVisibility controls which built-in TUI chrome elements are visible. // The zero value shows everything (backward compatible). type UIVisibility struct { HideStartupMessage bool // Hide the "Model loaded..." startup block HideStatusBar bool // Hide the "~/path (branch) ... provider · model" line HideSeparator bool // Hide the queued/steering count above the composer // HideInputHint is retained for compatibility and has no effect. The // submit hint is no longer a separate line below the composer; it lives // in the placeholder and disappears as soon as the user types. HideInputHint bool // HideMCPStartupMessages hides the message for each MCP server that has // loaded. It does not hide failure messages. HideMCPStartupMessages bool // HideLogo hides the wordmark at the top of the startup block, and its // animation. The model line and the list of loaded items stay. HideLogo bool } // AppModelOptions holds configuration passed to NewAppModel. type AppModelOptions struct { // ModelName is the display name of the model (e.g. "claude-sonnet-4-5"). ModelName string // ProviderName is the LLM provider (e.g. "anthropic", "openai"). // Used for the startup "Model loaded" message. ProviderName string // LoadingMessage is an optional informational message from the agent // (e.g. GPU fallback info). Displayed at startup when non-empty. LoadingMessage string // Cwd is the working directory for @file autocomplete and path resolution. // If empty, @file features are disabled. Cwd string // Shell is the shell the ! and !! commands run through: the shell plus // its own leading arguments. Empty means the built-in default, bash. Shell []string // Width is the initial terminal width in columns. Width int // Height is the initial terminal height in rows. Height int // ServerNames holds loaded MCP server names for the /servers command. ServerNames []string // ToolNames holds available tool names for the /tools command. ToolNames []string // GetToolNames, if non-nil, returns the current tool names. Called on // MCPToolsReadyEvent to refresh the tool list after background MCP tool // loading completes. May be nil if dynamic tool refresh is not needed. GetToolNames func() []string // GetMCPToolCount, if non-nil, returns the current MCP tool count. // Called on MCPToolsReadyEvent to refresh the startup info bar. // May be nil if dynamic tool refresh is not needed. GetMCPToolCount func() int // UsageTracker provides token usage statistics for /usage and /reset-usage. // May be nil if usage tracking is unavailable for the current model. UsageTracker *UsageTracker // ExtensionCommands are slash commands registered by extensions. They // appear in autocomplete, /help, and are dispatched when submitted. ExtensionCommands []commands.ExtensionCommand // PromptTemplates are user-defined prompt templates loaded from ~/.kit/prompts/, // .kit/prompts/, or explicit --prompt-template paths. They appear in autocomplete // and are expanded when submitted (e.g., /review → full prompt text). PromptTemplates []*prompts.PromptTemplate // GetPromptTemplates, if non-nil, returns the current prompt templates. // Called on ContentReloadEvent to refresh the template list after a file // watcher detects changes. May be nil if prompt hot-reload is not needed. GetPromptTemplates func() []*prompts.PromptTemplate // MCPPrompts are prompts discovered from MCP servers at startup. // They appear in autocomplete as /: commands. MCPPrompts []MCPPromptInfo // GetMCPPrompts, if non-nil, returns the current MCP prompts. // Called on MCPToolsReadyEvent to refresh after background loading. GetMCPPrompts func() []MCPPromptInfo // ExpandMCPPrompt, if non-nil, lazily expands an MCP prompt by // calling the MCP server's GetPrompt. Called asynchronously when the // user invokes an MCP prompt slash command. ExpandMCPPrompt func(serverName, promptName string, args map[string]string) (*MCPPromptExpandResult, error) // ContextPaths lists absolute paths of loaded context files (e.g. // AGENTS.md). Displayed in the [Context] startup section. ContextPaths []string // Bare reports that Kit started with no automatic context discovery. // The splash says so, so an absent AGENTS.md or skill list reads as a // deliberate choice rather than a failure to load. Bare bool // SkillItems lists loaded skills for the [Skills] startup section. SkillItems []SkillItem // GetSkillItems, if non-nil, returns the current skill items. // Called on ContentReloadEvent to refresh the skill list after a file // watcher detects changes. May be nil if skill hot-reload is not needed. GetSkillItems func() []SkillItem // ExtensionItems lists loaded extensions for the [Extensions] startup // section. Each entry shows the filename of an extension that was // discovered and loaded (global, project-local, or explicit). ExtensionItems []ExtensionItem // GetExtensionItems, if non-nil, returns the current extension items. // Called on extension hot-reload to refresh the list. May be nil if no // extensions are loaded. GetExtensionItems func() []ExtensionItem // MCPToolCount is the number of tools loaded from external MCP servers. MCPToolCount int // ExtensionToolCount is the number of tools registered by extensions. ExtensionToolCount int // GetWidgets returns current extension widgets for a given placement // ("above" or "below"). Called during View() to render persistent // extension widgets. May be nil if no extensions are loaded. GetWidgets func(placement string) []WidgetData // GetHeader returns the current custom header set by an extension, or // nil if no header is active. Called during View() to render a // persistent header above the stream region. May be nil. GetHeader func() *WidgetData // GetFooter returns the current custom footer set by an extension, or // nil if no footer is active. Called during View() to render a // persistent footer below the status bar. May be nil. GetFooter func() *WidgetData // GetToolRenderer returns the extension-provided tool renderer for a // specific tool name, or nil if no custom renderer is registered. // Called during tool result rendering to check for custom formatting. // May be nil if no extensions are loaded. GetToolRenderer func(toolName string) *ToolRendererData // GetEditorInterceptor returns the current editor interceptor set by // an extension, or nil if none is active. Called during Update() to // intercept key events and during View() to wrap input rendering. // May be nil if no extensions are loaded. GetEditorInterceptor func() *EditorInterceptor // GetUIVisibility returns the current UI visibility overrides set by // an extension, or nil if none have been set (show everything). // Called during View() to conditionally hide // built-in chrome elements. May be nil if no extensions are loaded. GetUIVisibility func() *UIVisibility // GetStatusBarEntries returns extension-provided status bar entries, // sorted by priority. Called during renderStatusBar() to inject // extension entries alongside the built-in model/usage display. // May be nil if no extensions are loaded. GetStatusBarEntries func() []StatusBarEntryData // EmitBeforeFork, if non-nil, is called before branching to a // different session tree entry. Returns (cancelled, reason) where // cancelled=true means the fork should be aborted. May be nil if // no extensions are loaded. EmitBeforeFork func(targetID string, isUserMsg bool, userText string) (bool, string) // EmitBeforeSessionSwitch, if non-nil, is called before switching // to a new session branch (e.g. /new, /clear). reason is the trigger // ("new", "clear", "extension"); initialPrompt is the user prompt // that will run as the first turn of the new session (empty when // /new is called without arguments). Returns (cancelled, reason). // May be nil if no extensions are loaded. EmitBeforeSessionSwitch func(reason, initialPrompt string) (bool, string) // GetGlobalShortcuts, if non-nil, returns extension-registered global // keyboard shortcuts. Keys are binding strings (e.g., "ctrl+p"). // Handlers are called in a goroutine to avoid blocking the TUI event // loop. May be nil if no extensions are loaded. GetGlobalShortcuts func() map[string]func() // GetShortcutList, if non-nil, returns the registered extension shortcuts // for the /shortcuts listing, sorted for display. May be nil if no // extensions are loaded. GetShortcutList func() []ShortcutInfo // GetExtensionCommands, if non-nil, returns the current extension // commands. Called on WidgetUpdateEvent to refresh the command list // after an extension hot-reload. May be nil if no extensions loaded. GetExtensionCommands func() []commands.ExtensionCommand // SetModel changes the active model at runtime. The model string uses // "provider/model" format (e.g. "anthropic/claude-sonnet-4-5-20250929"). // Returns an error if the model string is invalid or the provider cannot // be created. May be nil if model switching is not supported. SetModel func(modelString string) error // ProviderError is the error that kept the model provider from being // created at startup (missing credentials, a failed OAuth token // refresh, an unsupported provider, and so on). When non-nil the TUI // greets the user with a notice, opens the model selector so they can // pick a working model, refuses to send prompts, and clears the error // once /connect or /model installs a working provider. ProviderError error // SaveProviderAPIKey stores an API key for a provider (backs /connect). // May be nil, in which case /connect reports that key storage is // unavailable. SaveProviderAPIKey func(providerID, key string) error // EmitModelChange fires the OnModelChange extension event after a // successful model switch. Parameters are (newModel, previousModel, source). // May be nil if extensions are not loaded. EmitModelChange func(newModel, previousModel, source string) // EmitThinkingLevelChange fires the OnThinkingLevelChange extension // event. May be nil when no extensions are loaded. EmitThinkingLevelChange func(newLevel, previousLevel, source string) // EmitTerminalResize fires the OnTerminalResize extension event and // refreshes the terminal size on the extension context. May be nil. EmitTerminalResize func(width, height int) // ReadTerminalCapabilities applies remote terminal settings on the UI goroutine. // Called on window-size events and /refresh. Nil selects local terminal queries. ReadTerminalCapabilities func() error // EmitTurnStateChange fires the OnTurnStateChange extension event when // the UI enters or leaves the working state. May be nil. EmitTurnStateChange func(state, previous string) // EmitMCPToolsReady fires the OnMCPToolsReady extension event once // background MCP loading has finished. May be nil. EmitMCPToolsReady func() // KillSession stops the hosted daemon session. A nil callback makes /kill quit Kit. KillSession func() error // SwitchSession opens a session by JSONL file path, replacing the // active tree session and reloading messages. Called when the user // picks a session from /resume. May be nil if session switching is // not supported. SwitchSession func(path string) error // ShowSessionPicker, when true, opens the session picker immediately // on startup (used by --resume flag). ShowSessionPicker bool // StartupExtensionMessages are messages captured during extension // initialization. They are displayed in the ScrollList at startup. StartupExtensionMessages []string // ReloadExtensions hot-reloads all extensions from disk. Called by // the /reload-ext command and the automatic file watcher. May be nil // if no extensions are loaded. ReloadExtensions func() error // ThinkingLevel is the initial thinking level (e.g. "off", "medium"). ThinkingLevel string // ModelMode is the active catalog mode. Empty selects the model default. ModelMode string // ModelModes lists catalog modes; unsupported entries include a reason. ModelModes []ModelModeOption // IsReasoningModel is true when the current model supports reasoning. IsReasoningModel bool // SetThinkingLevel changes the thinking level on the agent/provider. SetThinkingLevel func(level string) error SetModelMode func(mode string) error // GetMCPResources, if non-nil, returns FileSuggestion entries for all // MCP resources available from connected servers. Used by the @ // autocomplete popup to merge resource suggestions with local files. GetMCPResources func() []FileSuggestion // MCPResourceReader, if non-nil, reads an MCP resource by server name // and URI. Used at submit time to resolve @mcp:server:uri tokens. MCPResourceReader fileutil.MCPResourceReader } // AppModel is the root Bubble Tea model for the interactive TUI. It owns the // state machine, routes events to child components, and manages the overall // layout. It holds a reference to the app layer (AppController) for triggering // agent work and queue operations. // // Layout (alt screen): // // ┌─ [custom header] (optional, from extension) ──────┐ // ├─ scroll region (variable height, ScrollList) ─────┤ // │ (completed messages + live streaming text) │ // ├─ separator line (with optional queue count) ───────┤ // │ [above widgets] │ // │ queued How do I fix the build? │ // │ queued Also check the tests │ // ├─ input region (fixed height from textarea) ────────┤ // │ [below widgets] │ // │ Tokens: 23.4K (12%) | Cost: $0.00 provider·model │ // ├─ [custom footer] (optional, from extension) ──────┤ // └────────────────────────────────────────────────────┘ // // The status bar is always present (1 line) to avoid layout shifts that // occurred when usage info appeared/disappeared conditionally. // // All messages (completed and streaming) are rendered via the ScrollList // viewport. The alt screen owns the full terminal. type AppModel struct { // conversationPane is the transcript pane on screen: parentPane, or the // pane of the subagent run that the user views (see childView). It is // embedded so that the transcript code reads m.messages, m.stream and // the other pane fields of whichever agent is shown. *conversationPane // parentPane is the parent agent's pane. It stays the same while a // subagent pane is shown. parentPane *conversationPane // childPanes holds one pane per subagent run, keyed by run ID. A pane is // made when the first update of its run arrives, so that it is complete // when the user opens it. childPanes map[string]*conversationPane // childView is non-nil while a subagent pane is shown. childView *childView // paneRequest is a pane switch that Update applies after the message is // handled, so that the shown pane never changes during a handler. paneRequest *paneRequest // state is the current state machine state. state appState // appCtrl is the app layer reference. Used to call Run(), CancelCurrentStep(), etc. // Accepts *app.App via the AppController interface. appCtrl AppController // input is the child input component (slash commands + autocomplete). input inputComponentIface imagePreview *imagePreviewModal inputYOffset int imagePreviewGeneration int // sheet is the open read-only sheet (/help and the info commands); nil // while closed. sheet *sheetModal // modelName is the LLM model name shown in rendered messages. modelName string // queuedMessages stores the text of prompts that were queued (not yet // submitted to the agent). They are rendered with a "queued" badge above // the input and move to the ScrollList when the agent picks them up. queuedMessages []string // steeringMessages stores the text of prompts that were sent as steer // messages (injected mid-turn via Ctrl+X s). Rendered with a "STEERING" // badge above the input. Cleared when the steer is consumed. steeringMessages []string // pendingUserPrints holds user messages that have been consumed from the // queue but not yet added to the ScrollList. They are deferred until // SpinnerEvent{Show: true} so the previous assistant response can be // flushed first, preserving chronological order. pendingUserPrints []string // lastHeaderHeight is the extension header height measured by the most // recent distributeHeight() pass. Used by currentScrollbackBounds so // mouse handlers don't re-render the header on every motion event. lastHeaderHeight int // chrome caches the fully rendered layout chrome (header, footer, // widgets, queued messages, input) measured by distributeHeight() so // View() can reuse the strings instead of rendering everything twice in // the same frame. Only valid within a single frame: View() invalidates // it on entry before recomputing layout. chrome chromeCache // newSessionResultCh, when non-nil, receives the outcome of an // in-flight extension-triggered NewSession request. Set when an // app.NewSessionRequestEvent arrives; cleared (with a result sent) // in performNewSession success/failure paths or in the // beforeSessionSwitchResultMsg cancellation path. newSessionResultCh chan<- error // canceling tracks whether the user has pressed ESC once during stateWorking. // A second ESC within 2 seconds will cancel the current step. canceling bool // leaderKeyActive tracks whether the Ctrl+X leader key prefix has been // pressed. The next keypress is interpreted as a chord suffix (e.g. "s" // for steer). Cleared on any subsequent keypress. leaderKeyActive bool // providerName is the LLM provider for the startup message. providerName string // loadingMessage is an optional agent startup message (e.g. GPU fallback). loadingMessage string // serverNames, toolNames are used by /servers and /tools commands. serverNames []string toolNames []string getToolNames func() []string // dynamic tool name provider (for MCP refresh) // getMCPToolCount returns the current MCP tool count dynamically. getMCPToolCount func() int // usageTracker provides token usage stats for /usage and /reset-usage. // May be nil when usage tracking is unavailable. usageTracker *UsageTracker // extensionCommands are slash commands from extensions, dispatched via // handleExtensionCommand when submitted. extensionCommands []commands.ExtensionCommand // promptTemplates are user-defined prompt templates for expansion. // They appear in autocomplete and are expanded when submitted. promptTemplates []*prompts.PromptTemplate // getPromptTemplates returns the current prompt templates. Used to // refresh the template list after content hot-reload. May be nil. getPromptTemplates func() []*prompts.PromptTemplate // mcpPrompts are prompts discovered from MCP servers, shown as // /: slash commands. mcpPrompts []MCPPromptInfo // getMCPPrompts returns the current MCP prompts. Called on // MCPToolsReadyEvent to refresh after background loading. getMCPPrompts func() []MCPPromptInfo // expandMCPPrompt lazily expands an MCP prompt via the server. expandMCPPrompt func(serverName, promptName string, args map[string]string) (*MCPPromptExpandResult, error) // treeSelector is the tree navigation overlay, active in stateTreeSelector. treeSelector *TreeSelectorComponent // contextPaths and skillItems are used by AddStartupMessageToScrollList for the // [Context] and [Skills] sections. contextPaths []string // bare reports that no automatic context discovery ran. bare bool skillItems []SkillItem // splashItem is the scrollback item holding the startup splash, retained // while the logo animation is running so each frame can be painted into // it in place. Cleared once the animation settles. splashItem *TextMessageItem // splashTail is the part of the splash below the wordmark (the model line // and the list of what was loaded), kept so animation frames rebuild only // the logo rather than re-deriving the whole block. splashTail []string // logoFrame is the startup animation's current frame. The animation does // not own a tick loop; it advances when the shared frame clock hands it a // frame, and reports through wantsFrames that it wants more. logoFrame int // frames is the shared animation clock. Every animated component in the // app advances on its beat; see frameclock.go for why there is only one. frames frameClock // widgetRenders caches output from animated extension widgets, keyed by // widget ID (headers and footers use synthetic keys). widgetRenders map[string]widgetRenderCache // fillActive requires a layout pass each frame so View reuses sized chrome. fillActive bool // renderEpoch increments once per View() pass. Widget Render callbacks // are cached against it so the measurement pass in distributeHeight and // the paint pass in View always see identical content — a time-varying // widget would otherwise be able to measure N lines and paint N+1. renderEpoch int // getSkillItems returns the current skill items. Used to refresh the // skill list after content hot-reload. May be nil. getSkillItems func() []SkillItem // extensionItems lists loaded extensions for the [Extensions] startup // section (filenames only). extensionItems []ExtensionItem // getExtensionItems returns the current extension items. Used to refresh // the list after extension hot-reload. May be nil. getExtensionItems func() []ExtensionItem // mcpToolCount and extensionToolCount track tool counts by source for // the startup info display. mcpToolCount int extensionToolCount int // startupExtensionMessages stores messages from extensions during initialization. startupExtensionMessages []string // getWidgets returns extension widgets for a given placement. May be nil. getWidgets func(placement string) []WidgetData // getHeader returns the current custom header. May be nil. getHeader func() *WidgetData // getFooter returns the current custom footer. May be nil. getFooter func() *WidgetData // getEditorInterceptor returns the current editor interceptor. May be nil. getEditorInterceptor func() *EditorInterceptor // getUIVisibility returns extension-provided UI visibility overrides. May be nil. getUIVisibility func() *UIVisibility // getStatusBarEntries returns extension-provided status bar entries. May be nil. getStatusBarEntries func() []StatusBarEntryData // emitBeforeFork emits a before-fork event to extensions. Returns // (cancelled, reason). May be nil if no extensions are loaded. emitBeforeFork func(targetID string, isUserMsg bool, userText string) (bool, string) // emitBeforeSessionSwitch emits a before-session-switch event to extensions. // Returns (cancelled, reason). May be nil if no extensions are loaded. emitBeforeSessionSwitch func(reason, initialPrompt string) (bool, string) // thinkingLevel is the current extended thinking level. thinkingLevel string modelMode string modelModes []ModelModeOption setModelMode func(mode string) error // thinkingVisible controls whether reasoning blocks are shown or collapsed. thinkingVisible bool // isReasoningModel is true when the current model supports reasoning. isReasoningModel bool // setThinkingLevel is a callback to change the thinking level on the agent. // It takes the new level string and returns an error if the change fails. setThinkingLevel func(level string) error // getGlobalShortcuts returns extension-registered keyboard shortcuts. // May be nil if no extensions are loaded. getGlobalShortcuts func() map[string]func() // getShortcutList returns extension shortcuts for the /shortcuts listing. getShortcutList func() []ShortcutInfo // getExtensionCommands returns the current extension commands. Used // to refresh the command list after an extension hot-reload. May be nil. getExtensionCommands func() []commands.ExtensionCommand // setModel changes the active model at runtime. Wired from cmd/root.go. // May be nil if model switching is not supported. setModel func(modelString string) error // providerError is non-nil while the active model has no usable // provider (no API key). See AppModelOptions.ProviderError. providerError error // saveProviderAPIKey stores a provider API key. Wired from cmd/root.go. saveProviderAPIKey func(providerID, key string) error // providerConnect is the /connect dialog, active in stateProviderConnect. providerConnect *ProviderConnectComponent // emitModelChange fires the OnModelChange extension event. May be nil. emitModelChange func(newModel, previousModel, source string) // emitThinkingLevelChange fires the OnThinkingLevelChange extension // event. May be nil. emitThinkingLevelChange func(newLevel, previousLevel, source string) // emitTerminalResize fires the OnTerminalResize extension event. May be nil. emitTerminalResize func(width, height int) readTerminalCapabilities func() error // emitTurnStateChange fires the OnTurnStateChange extension event. May be nil. emitTurnStateChange func(state, previous string) // emitMCPToolsReady fires the OnMCPToolsReady extension event. May be nil. emitMCPToolsReady func() // extEvents serializes extension event dispatch so that rapid events // reach the runner in emission order. See ext_event_dispatcher.go. extEvents *extEventDispatcher // modelSelector is the model selection overlay, active in stateModelSelector. modelSelector *ModelSelectorComponent // thinkingLevelSelector is the reasoning-effort picker, active in // stateThinkingLevelSelector. thinkingLevelSelector *ThinkingLevelSelectorComponent modelModeSelector *ModelModeSelectorComponent // killSubagentSelector is the /kill-subagent picker. It is not tied to // an appState: subagents run while the agent works, so the state stays // stateWorking and keys are routed here while this is non-nil. killSubagentSelector *KillSubagentSelectorComponent subagentRunPicker *SubagentRunPicker // themeSelector is the color-theme picker, active in stateThemeSelector. themeSelector *ThemeSelectorComponent // sessionSelector is the session picker overlay, active in stateSessionSelector. sessionSelector *SessionSelectorComponent // reloadExtensions hot-reloads all extensions from disk. May be nil. reloadExtensions func() error // switchSession opens a session by JSONL path, replacing the active session. // Wired from cmd/root.go. switchSession func(path string) error killSession func() error killConfirm bool // prompt holds the state of an active interactive prompt overlay. Nil // when no prompt is active. Managed by updatePromptState(). prompt *promptOverlay // promptResponseCh is the write-side of the channel used to deliver the // user's prompt answer back to the blocking extension goroutine. Set // alongside prompt; nil when no prompt is active. promptResponseCh chan<- app.PromptResponse // prePromptState remembers the state before the prompt overlay took // over, so the model can return to it when the prompt completes. prePromptState appState // overlay holds the state of an active modal overlay dialog. Nil when // no overlay is active. Managed by updateOverlayState(). overlay *overlayDialog // overlayResponseCh is the write-side of the channel used to deliver // the user's overlay response back to the blocking extension goroutine. // Set alongside overlay; nil when no overlay is active. overlayResponseCh chan<- app.OverlayResponse // preOverlayState remembers the state before the overlay took over, // so the model can return to it when the overlay completes. preOverlayState appState // navReturnState remembers the state message navigation suspended, so // exiting navigation returns to it rather than unconditionally to // stateInput. Agent lifecycle transitions that land while navigation // owns the keyboard are recorded here instead of being applied (see // setAgentState), so a turn that starts or finishes mid-browse is // reflected the moment the user presses Esc. navReturnState appState // navNotice is a one-shot acknowledgement shown in the status bar's // navigation slot — currently only the result of a copy. // // Navigation feedback cannot use printSystemMessage: that appends an item // to the very list being navigated, which shifts the frame's position // counter and can move the selection off screen. The notice is cleared by // the next navigation keystroke. navNotice string // navCopied is the number of characters of the copy that navNotice // acknowledges, so the notice can say when the copy missed the system // clipboard. Every site that sets navNotice sets it too. navCopied int // clipboardNote reports a failed write to the system clipboard. It waits // for a quiet scrollback (see quietScrollback). clipboardNoted makes the // report appear only once. clipboardNote string clipboardNoted bool // clipboardFailed records that the latest copy did not reach the system // clipboard, so that the status bar does not claim it did. clipboardFailed bool // cwd is the working directory for @file path resolution. cwd string shell []string // shell for the ! and !! commands; empty means bash // gitBranch is the current git branch name, resolved once when cwd is // set. Empty when the working directory is not a git repository. Shown // in the ambient status bar. gitBranch string // lastInputHeight is the composer height measured by the last // distributeHeight. The composer grows and shrinks with its content, so // this is compared after every input update to detect a size change that // requires the transcript to be resized. See syncInputHeight. lastInputHeight int // lastActivityPresent records whether the activity row was rendered by the // last distributeHeight. The row appears when the agent starts working and // disappears when it stops, and nothing in that transition otherwise marks // the layout dirty, so it is compared every frame. See syncActivityRow. lastSubagentStatusPresent bool subagentStatusCheckedAt time.Time subagentStatusCache []kit.SubagentRun lastActivityPresent bool // mcpResourceReader is an optional callback to read MCP resources when // processing @mcp:server:uri tokens at submit time. Set by the parent. mcpResourceReader fileutil.MCPResourceReader // width and height track the terminal dimensions. width int height int // quitting signals that the app is shutting down. When true, View() // disables alt screen to restore the terminal properly. quitting bool // ctrlCPressedOnce tracks if Ctrl+C was pressed once to clear input. // A second Ctrl+C (or Ctrl+C when input is empty) will quit the app. ctrlCPressedOnce bool // ---------- Cached layout heights (invalidated by layoutDirty) ---------- // layoutDirty marks that distributeHeight must recompute the stream height // on the next View() call. Set by any state change that affects sizing // (resize, queue changes, widget updates, visibility changes, etc.). // View() calls distributeHeight() when this is true and then clears it. layoutDirty bool // gfxPlacement is the escape sequence that redraws directly-placed preview // images at their current screen position, or "" when there are none. // // A direct placement is painted over the screen rather than being part of // the view. View computes it, because only View knows the final row of // every element, and Update writes it, because escape sequences cannot // travel inside view text. // // Only terminals that need ModeDirect use this; see internal/ui/termgfx. gfxPlacement string // gfxDirty records that the screen has been repainted since the image was // last placed, so it must be drawn again. // // Re-placing only when the computed row changes is not enough. The // renderer scrolls the screen to update it, and a terminal scrolls its // images along with the text, so an image drifts upward while the row it // belongs on stays exactly the same. Redrawing whenever the frame content // changes catches that; gfxContentHash is what detects the change. gfxDirty bool gfxFlushPending bool gfxPendingDrops map[uint32]struct{} // gfxContentHash is a hash of the last rendered frame, used to notice that // the screen was repainted. gfxContentHash uint64 // gfxPlaced holds the id of every image that the last computed placement // left painted on the screen. // // A directly-placed image is not part of the view, so redrawing the cells // underneath does not remove it: an image whose message has scrolled out of // the viewport, or that a modal now covers, has to be told to go. Comparing // this set against the images the current frame draws is how the ones that // vanished are found. gfxPlaced map[uint32]struct{} // pendingGotoBottom requests a GotoBottom() after the next layout // recalculation. Set when loading a session so that scrolling to the // bottom happens with the correct viewport height. pendingGotoBottom bool // scrollbackYOffset is the Y coordinate where the scrollback area starts // on screen (after header). Mouse Y coordinates must be adjusted by this // offset before being passed to the ScrollList. scrollbackYOffset int } // -------------------------------------------------------------------------- // Child component interfaces // -------------------------------------------------------------------------- // inputComponentIface is the interface the parent requires from InputComponent. type inputComponentIface interface { tea.Model } // streamComponentIface is the interface the parent requires from StreamComponent. type streamComponentIface interface { tea.Model // Reset clears accumulated state between agent steps. Reset() // GetRenderedContent returns the rendered assistant message from accumulated // streaming text, or empty string if nothing has been accumulated. GetRenderedContent() string // ActivityDot returns the animated indicator glyph on its own, for the // activity row. Returns "" when nothing is in flight. ActivityDot() string // IsSpinning reports whether there is live activity being animated. The // parent reads this to decide whether the shared frame clock should keep // running. IsSpinning() bool // ActivityPhrase returns a present-tense description of the work currently // in flight, e.g. "Running go test ./...". ActivityPhrase() string // SetThinkingVisible sets whether reasoning blocks are shown or collapsed. SetThinkingVisible(visible bool) // HasReasoning returns true if any reasoning content has been accumulated. HasReasoning() bool // UpdateTheme refreshes typography with colors from the current theme. UpdateTheme() } // -------------------------------------------------------------------------- // Constructor // -------------------------------------------------------------------------- // NewAppModel creates a new AppModel. The appCtrl parameter must not be nil. // opts provides display configuration; zero values are valid (uses defaults). // // To use with the concrete *app.App type, pass it directly — *app.App // satisfies AppController once the app layer is implemented (TAS-4). // // NewAppModel constructs all child components (InputComponent, StreamComponent) // using the provided options. func NewAppModel(appCtrl AppController, opts AppModelOptions) *AppModel { width := opts.Width if width == 0 { width = 80 // sensible fallback } height := opts.Height if height == 0 { height = 24 // sensible fallback } mr := newMessageRenderer(width, false) mr.getToolRenderer = opts.GetToolRenderer rdr := mr m := &AppModel{ conversationPane: &conversationPane{renderer: rdr}, state: stateInput, appCtrl: appCtrl, modelName: opts.ModelName, providerName: opts.ProviderName, loadingMessage: opts.LoadingMessage, serverNames: opts.ServerNames, toolNames: opts.ToolNames, getToolNames: opts.GetToolNames, getMCPToolCount: opts.GetMCPToolCount, usageTracker: opts.UsageTracker, cwd: opts.Cwd, shell: opts.Shell, width: width, height: height, } // Store extension commands for dispatch. m.extensionCommands = opts.ExtensionCommands m.promptTemplates = opts.PromptTemplates m.getPromptTemplates = opts.GetPromptTemplates m.mcpPrompts = opts.MCPPrompts m.getMCPPrompts = opts.GetMCPPrompts m.expandMCPPrompt = opts.ExpandMCPPrompt m.getWidgets = opts.GetWidgets m.getHeader = opts.GetHeader m.getFooter = opts.GetFooter m.getEditorInterceptor = opts.GetEditorInterceptor m.getUIVisibility = opts.GetUIVisibility m.getStatusBarEntries = opts.GetStatusBarEntries m.emitBeforeFork = opts.EmitBeforeFork m.emitBeforeSessionSwitch = opts.EmitBeforeSessionSwitch m.getGlobalShortcuts = opts.GetGlobalShortcuts m.getShortcutList = opts.GetShortcutList m.getExtensionCommands = opts.GetExtensionCommands m.setModel = opts.SetModel m.providerError = opts.ProviderError m.saveProviderAPIKey = opts.SaveProviderAPIKey m.emitModelChange = opts.EmitModelChange m.emitThinkingLevelChange = opts.EmitThinkingLevelChange m.emitTerminalResize = opts.EmitTerminalResize m.readTerminalCapabilities = opts.ReadTerminalCapabilities m.emitTurnStateChange = opts.EmitTurnStateChange m.emitMCPToolsReady = opts.EmitMCPToolsReady m.extEvents = newExtEventDispatcher() m.thinkingLevel = opts.ThinkingLevel m.modelMode = opts.ModelMode m.modelModes = opts.ModelModes m.setModelMode = opts.SetModelMode m.thinkingVisible = true // default to showing thinking blocks m.isReasoningModel = opts.IsReasoningModel m.setThinkingLevel = opts.SetThinkingLevel m.switchSession = opts.SwitchSession m.killSession = opts.KillSession m.reloadExtensions = opts.ReloadExtensions // Store context/skills metadata and tool counts for startup display. m.contextPaths = opts.ContextPaths m.bare = opts.Bare m.skillItems = opts.SkillItems m.getSkillItems = opts.GetSkillItems m.extensionItems = opts.ExtensionItems m.getExtensionItems = opts.GetExtensionItems m.mcpToolCount = opts.MCPToolCount m.extensionToolCount = opts.ExtensionToolCount m.startupExtensionMessages = opts.StartupExtensionMessages // Initialize streaming bash output buffer. m.streamingBashMaxLines = 50 // cap to prevent memory issues // Initialize ScrollList for in-memory message history (alt screen mode). // Height will be set properly by distributeHeight(). m.scrollList = NewScrollList(width, height-10) // Placeholder height m.messages = []MessageItem{} m.parentPane = m.conversationPane // Wire up child components now that we have the concrete implementations. m.input = NewInputComponent(width, appCtrl) // Wire up cwd for @file autocomplete. if ic, ok := m.input.(*InputComponent); ok && opts.Cwd != "" { ic.SetCwd(opts.Cwd) } // Resolve the git branch once at startup for the ambient status bar. // A miss is not an error — the branch is simply omitted. m.gitBranch = detectGitBranch(opts.Cwd) // Wire up MCP resource provider for @ autocomplete. if ic, ok := m.input.(*InputComponent); ok && opts.GetMCPResources != nil { ic.SetMCPResourceProvider(opts.GetMCPResources) } // Wire up MCP resource reader for @mcp: token processing at submit time. m.mcpResourceReader = opts.MCPResourceReader // Merge extension commands into the InputComponent's autocomplete source. if ic, ok := m.input.(*InputComponent); ok && len(opts.ExtensionCommands) > 0 { for _, ec := range opts.ExtensionCommands { ic.commands = append(ic.commands, commands.SlashCommand{ Name: ec.Name, Description: ec.Description, Category: "Extensions", Complete: ec.Complete, }) } } // Merge prompt templates into the InputComponent's autocomplete source. if ic, ok := m.input.(*InputComponent); ok && len(opts.PromptTemplates) > 0 { for _, tpl := range opts.PromptTemplates { ic.commands = append(ic.commands, commands.SlashCommand{ Name: "/" + tpl.Name, Description: tpl.Description, Category: "Prompts", HasArgs: tpl.HasArgPlaceholders(), }) } } // Merge skills into autocomplete as / commands (the agentskills.io // user-explicit activation convention). Skills accept optional trailing // args, so HasArgs is true — Enter populates the input with "/name " // rather than auto-submitting. A skill whose name is already taken by a // built-in command, extension command or prompt template is shadowed at // dispatch time, so it is left out of the popup and logged. if ic, ok := m.input.(*InputComponent); ok && len(opts.SkillItems) > 0 { ic.commands = appendSkillCommands(ic.commands, opts.SkillItems) } // Merge MCP prompts into autocomplete as /: commands. if ic, ok := m.input.(*InputComponent); ok && len(opts.MCPPrompts) > 0 { for _, p := range opts.MCPPrompts { hasArgs := false for _, a := range p.Arguments { if a.Required { hasArgs = true break } } ic.commands = append(ic.commands, commands.SlashCommand{ Name: fmt.Sprintf("/%s:%s", p.ServerName, p.Name), Description: p.Description, Category: "MCP Prompts", HasArgs: hasArgs, }) } } m.stream = NewStreamComponent(width, opts.ModelName) m.stream.SetThinkingVisible(m.thinkingVisible) // If --resume was passed, open the session picker immediately. if opts.ShowSessionPicker { m.sessionSelector = NewSessionSelector(appCtrl, opts.Cwd, width, height) m.state = stateSessionSelector } // The configured provider could not be created at startup (missing // credentials, a failed OAuth token refresh, an unsupported provider, // and so on). Open the model selector immediately so the user can pick // a working model instead of being stuck on a dead one. The session // picker (--resume) takes precedence when both are requested; the // selector opens once that picker closes. if !opts.ShowSessionPicker { m.openModelSelectorForProviderError() } // Propagate initial height distribution to children. m.distributeHeight() return m } // -------------------------------------------------------------------------- // tea.Model interface // -------------------------------------------------------------------------- // Init implements tea.Model. Initialises child components. func (m *AppModel) Init() tea.Cmd { // Add startup info to ScrollList so it's visible in alt screen mode m.AddStartupMessageToScrollList() // m.input is always set by NewAppModel; its Init starts the textarea cursor blink. // m.stream.Init() always returns nil, so there is nothing to batch. // The logo animation is nil unless the terminal can render it. if anim := m.startLogoAnimation(); anim != nil { return tea.Batch(m.input.Init(), anim) } return m.input.Init() } // uiVis returns the current UIVisibility, defaulting to zero value (show all) // if no extension has set visibility overrides. func (m *AppModel) uiVis() UIVisibility { if m.getUIVisibility != nil { if v := m.getUIVisibility(); v != nil { return *v } } return UIVisibility{} } // AddStartupMessageToScrollList adds the logo and startup info as the first // messages in the ScrollList. This is the only place startup information is // rendered — nothing is printed to stdout. func (m *AppModel) AddStartupMessageToScrollList() { vis := m.uiVis() if vis.HideStartupMessage { return } // The splash is one block: the wordmark, the active model, and an aligned // list of what was loaded, indented to the shared content column. theme := style.GetTheme() labelStyle := lipgloss.NewStyle().Foreground(theme.VeryMuted) valueStyle := lipgloss.NewStyle().Foreground(theme.Muted) // The wordmark leads, and is kept separate from everything below it so // the startup animation can repaint just the logo without rebuilding the // rest of the block on every frame. var tail []string tail = append(tail, "") if m.providerName != "" && m.modelName != "" { tail = append(tail, valueStyle.Render(m.providerName+" · "+m.modelName)) } else if m.modelName != "" { tail = append(tail, valueStyle.Render(m.modelName)) } // Build key-value pairs for startup info. var pairs [][2]string if m.loadingMessage != "" { pairs = append(pairs, [2]string{"status", m.loadingMessage}) } // Context — loaded AGENTS.md files. Bare mode reports itself instead, so // the absence of context below is legible as intent. if m.bare { pairs = append(pairs, [2]string{"context", "bare — no project context"}) } else if len(m.contextPaths) > 0 { contextStr := tildeHome(m.contextPaths[0]) if len(m.contextPaths) > 1 { contextStr += fmt.Sprintf(" +%d more", len(m.contextPaths)-1) } pairs = append(pairs, [2]string{"context", contextStr}) } // Skills — listed by name. if len(m.skillItems) > 0 { names := make([]string, len(m.skillItems)) for i, si := range m.skillItems { names[i] = si.Name } pairs = append(pairs, [2]string{"skills", strings.Join(names, ", ")}) } // Extensions — listed by filename, with a tool count when they register // tools. Falls back to a bare count if the CLI supplied no item list. if len(m.extensionItems) > 0 { names := make([]string, len(m.extensionItems)) for i, ei := range m.extensionItems { names[i] = ei.Name } value := strings.Join(names, ", ") if m.extensionToolCount > 0 { value += fmt.Sprintf(" (%d tools)", m.extensionToolCount) } pairs = append(pairs, [2]string{"extensions", value}) } else if m.extensionToolCount > 0 { pairs = append(pairs, [2]string{"extensions", fmt.Sprintf("%d tools", m.extensionToolCount)}) } // MCP tool count (only shown when > 0). if m.mcpToolCount > 0 { pairs = append(pairs, [2]string{"mcp", fmt.Sprintf("%d tools", m.mcpToolCount)}) } if len(pairs) > 0 { // Align values into a column so the list scans vertically. labelWidth := 0 for _, p := range pairs { if w := lipgloss.Width(p[0]); w > labelWidth { labelWidth = w } } tail = append(tail, "") for _, p := range pairs { label := labelStyle.Render(p[0] + strings.Repeat(" ", labelWidth-lipgloss.Width(p[0]))) tail = append(tail, label+" "+valueStyle.Render(p[1])) } } m.splashTail = tail if vis.HideLogo { // Without the wordmark there is nothing to animate, so splashItem // stays nil. The block keeps the indent and spacing of the splash, // without the blank line that follows the wordmark. if lines := tail[1:]; len(lines) > 0 { m.messages = append(m.messages, NewThemedMessageItem(generateMessageID(), "logo", strings.Join(lines, "\n"), func() string { return style.SplashBlock(lines) })) } } else { // The splash starts at whichever frame the animation will begin // from, so there is no flash of the resting logo before the first // tick lands. m.logoFrame = m.initialLogoFrame() splash := m.renderSplash(m.logoFrame) // Themed so the banner follows a theme switch. The closure reads the // current frame, which is also what lets the animation repaint in // place. item := NewThemedMessageItem(generateMessageID(), "logo", splash, func() string { return m.renderSplash(m.logoFrame) }) m.splashItem = item m.messages = append(m.messages, item) } // No credentials for the configured provider: greet the user with the // fix instead of failing at startup. if m.providerError != nil { notice := m.providerErrorNotice() now := time.Now() m.messages = append(m.messages, NewThemedMessageItem(generateMessageID(), "system", notice, func() string { return m.renderer.RenderSystemMessage(notice, now).Content })) } // Add extension startup messages if any. These are ordinary system // notices and are rendered as such — appending the raw string would put // unstyled, unwrapped text at column 0. for _, extMsg := range m.startupExtensionMessages { now := time.Now() m.messages = append(m.messages, NewThemedMessageItem(generateMessageID(), "system", extMsg, func() string { return m.renderer.RenderSystemMessage(extMsg, now).Content })) } // The splash carries its own trailing gap, which is what separates the // startup banner from the conversation. A blank line is enough to break // the two apart, and it does not add a heavy horizontal element to an // otherwise quiet screen. // Refresh ScrollList once with all startup messages m.refreshContent() } // -------------------------------------------------------------------------- // Startup logo animation // -------------------------------------------------------------------------- // logoAnimationSupported reports whether the startup animation should run at // all. // // It is skipped on terminals without the colour depth to render a gradient // sweep (where it would strobe between a handful of steps rather than move), // and when the wordmark has degraded to a plain "KIT" because the terminal is // too narrow for the block art — there is nothing there to animate. // // The gate lives here, on the animation, rather than on the shared clock. The // clock also drives the activity spinner, which is a liveness indicator rather // than decoration and has to keep moving on a two-colour terminal. func (m *AppModel) logoAnimationSupported() bool { return style.SupportsSmoothAnimation() && style.KitLogoFits(m.width-style.ContentOffset) } // initialLogoFrame returns the frame the splash should first be rendered at: // the start of the animation when it will run, or the resting frame when it // will not. func (m *AppModel) initialLogoFrame() int { if m.logoAnimationSupported() { return 0 } return style.KitLogoAnimationFrames } // renderSplash rebuilds the startup block with the wordmark at the given // animation frame. func (m *AppModel) renderSplash(frame int) string { // The block is indented by ContentOffset, so that is what the logo has to // fit inside. content := make([]string, 0, len(m.splashTail)+style.KitLogoHeight) content = append(content, style.KitLogoLinesAt(m.width-style.ContentOffset, frame)...) content = append(content, m.splashTail...) return style.SplashBlock(content) } // startLogoAnimation arms the startup animation, returning the command that // starts the shared clock, or nil when the animation will not run. // // Arming is just resetting the frame counter: the retained splashItem is what // wantsFrames reads to keep the clock alive, and dropping it at the end of the // sweep is what lets the clock stop. func (m *AppModel) startLogoAnimation() tea.Cmd { if m.splashItem == nil || !m.logoAnimationSupported() { return nil } m.logoFrame = 0 return m.wakeFrameClock() } // advanceLogoAnimation paints the next animation frame into the splash item, // releasing it once the animation has settled. // // The splash is repainted in place rather than replaced: the item keeps its // ID, and every frame is the same height, so ScrollList's height cache stays // valid and the animation costs one re-render of a seven-line item per frame. func (m *AppModel) advanceLogoAnimation() { if m.splashItem == nil { return } m.logoFrame++ m.splashItem.Invalidate() m.refreshContent() if m.logoFrame >= style.KitLogoAnimationFrames { // Settled. Dropping the item reference both stops any later frame from // finding something to repaint and tells wantsFrames the animation is // over, which is what lets the clock wind down. splashTail is // deliberately kept, so renderSplash stays valid for any future caller // rather than silently rebuilding the block without its content. m.splashItem = nil } } // tildeHome replaces the user's home directory prefix with ~ for display. func tildeHome(path string) string { home, err := os.UserHomeDir() if err != nil { return path } if strings.HasPrefix(path, home) { return "~" + path[len(home):] } return path } // Update implements tea.Model. It routes incoming messages to children and // handles state transitions, then keeps the shared animation clock in step. // // The clock is woken here rather than at each site that starts an animation. // update has many early returns, and an animation can begin down any of them — // a spinner starting on a tool event, the logo starting on a resize — so a // wake call per site would be a standing invitation to miss one, and a missed // one is a permanently frozen animation. Doing it once, after update has run // and whatever it did has settled, makes the invariant total: if anything // wants frames, the clock is running. start is idempotent, so this costs // nothing on the overwhelming majority of messages, when the clock is either // already running or not wanted. func (m *AppModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { // Before any mode can consume them: the next key, paste or click ends // the selection kept after a mouse copy, and a failed write to the // system clipboard is noted for its report (see clipboardNote). switch msg := msg.(type) { case tea.KeyPressMsg, tea.PasteMsg, tea.MouseClickMsg: if m.scrollList != nil { m.scrollList.EndKeptSelection() } case clipboard.NativeCopyFailedMsg: m.clipboardFailed = true if !m.clipboardNoted { m.clipboardNoted = true m.clipboardNote = fmt.Sprintf( "Could not write the system clipboard (%s). Copies still go to the terminal as OSC 52, which not every terminal supports.", strings.TrimSuffix(msg.Err.Error(), ".")) } } // Handle capabilities before modal sub-loops can consume the message. var capabilityCmd tea.Cmd switch msg := msg.(type) { case tea.WindowSizeMsg: if m.readTerminalCapabilities != nil { dark, profile := style.IsDarkBackground(), style.ColorProfile() if err := m.readTerminalCapabilities(); err == nil && (dark != style.IsDarkBackground() || profile != style.ColorProfile()) { m.refreshTheme() capabilityCmd = terminalRepaintCmd() } } case tea.BackgroundColorMsg: if m.readTerminalCapabilities == nil { style.SetTerminalCapabilities(msg.IsDark(), style.ColorProfile()) m.refreshTheme() capabilityCmd = tea.ClearScreen } case tea.ColorProfileMsg: if m.readTerminalCapabilities == nil && msg.Profile != style.ColorProfile() { style.SetTerminalCapabilities(style.IsDarkBackground(), msg.Profile) m.refreshTheme() capabilityCmd = tea.ClearScreen } } var placementCmd tea.Cmd if _, ok := msg.(gfxFlushMsg); ok { placementCmd = m.completeGfxFlush() } model, cmd := m.routeUpdate(msg) if m.clipboardNote != "" && m.childView == nil && m.quietScrollback() { m.printSystemMessage(m.clipboardNote) m.clipboardNote = "" } cmds := []tea.Cmd{cmd, placementCmd} if capabilityCmd != nil { cmds = append(cmds, capabilityCmd) } // View marks graphics dirty only when the layout or frame changes. Do not // mark them dirty for every input event: mouse motion over a static preview // would repeatedly delete and redraw the image in the terminal. // Update precedes View. Check once after the final input event as well, // so changes discovered by that View do not need another user event. switch msg.(type) { case gfxFlushMsg, tea.RawMsg: default: if m.gfxPlacement != "" && !m.gfxDirty && !m.gfxFlushPending { m.gfxFlushPending = true cmds = append(cmds, tea.Tick(40*time.Millisecond, func(time.Time) tea.Msg { return gfxFlushMsg{} })) } } if gfx := m.flushGfxPlacement(); gfx != nil { cmds = append(cmds, gfx) } if wake := m.wakeFrameClock(); wake != nil { cmds = append(cmds, wake) } if len(cmds) == 1 { return model, cmd } return model, tea.Batch(cmds...) } // flushGfxPlacement returns a command that redraws directly-placed preview // images, or nil when their position has not changed since the last write. // // The sequence itself is computed by View, which is the only place that knows // the final screen row of every element. It is written from here because // escape sequences cannot travel inside view text: the renderer parses the // view into cells and would mangle them. // // The one-frame lag this implies is not visible in practice. Update runs // before View for a given message, so the placement written here belongs to // the previous frame; a frame that moves the image is therefore followed by a // corrective placement on the next event. Anything that changes the layout — // a keystroke, a resize, an agent event, the frame clock — produces that // event, and the image is re-placed against a screen the renderer has already // finished drawing. // gfxFlushMsg gives the renderer time to flush the frame before direct images // are placed. The latest View sequence is used, not a captured older layout. type gfxFlushMsg struct{} // completeGfxFlush writes the latest placement sequence and clears pending cleanup. func (m *AppModel) completeGfxFlush() tea.Cmd { m.gfxFlushPending = false if !m.gfxDirty { return nil } m.gfxDirty = false m.gfxPendingDrops = nil return tea.Raw(m.gfxPlacement) } // flushGfxPlacement schedules one delayed placement update while the frame settles. func (m *AppModel) flushGfxPlacement() tea.Cmd { if !m.gfxDirty || m.gfxFlushPending { return nil } if m.gfxPlacement == "" { m.gfxDirty = false return nil } m.gfxFlushPending = true return tea.Tick(40*time.Millisecond, func(time.Time) tea.Msg { return gfxFlushMsg{} }) } // wantsFrames reports whether any animation currently needs the clock. // // This is a pull, not a subscription registry. The animated components are // already owned by AppModel, so asking them is cheaper and harder to get wrong // than having each register and — the part that actually breaks — remember to // deregister on every exit path. func (m *AppModel) wantsFrames() bool { if m.splashItem != nil { return true } if m.stream != nil && m.stream.IsSpinning() { return true } if m.hasVisibleSubagentRuns() { return true } // An extension widget can hold the clock open for its own animation. // This is the only path by which a session with nothing else moving stays // awake, so it is deliberately gated on an explicit RefreshHz opt-in. return m.animatedWidgets() } // wakeFrameClock resumes the clock if something needs frames and it is idle, // returning nil in every other case. func (m *AppModel) wakeFrameClock() tea.Cmd { if !m.wantsFrames() { return nil } return m.frames.start() } // advanceFrame drives one beat of the shared clock: it hands the frame to // every animation that is due one, then either schedules the next beat or // stops the clock because nothing is animating any more. func (m *AppModel) advanceFrame(t frameTickMsg) tea.Cmd { if !m.frames.accept(t) { return nil } var cmds []tea.Cmd if m.splashItem != nil && t.due(frameEveryLogo) { m.advanceLogoAnimation() } // The spinner lives in StreamComponent, so the frame is handed to it the // same way any other message would be. It advances its own frame and // schedules nothing. if m.stream != nil { updated, cmd := m.stream.Update(t) m.stream, _ = updated.(streamComponentIface) cmds = append(cmds, cmd) } if !m.wantsFrames() { m.frames.stop() return tea.Batch(cmds...) } return tea.Batch(append(cmds, m.frames.tick())...) } // routeUpdate sends msg to the pane it belongs to and then applies any // pane switch that a handler requested. // // Subagent run updates and their stream flush ticks go to the child panes, // shown or not. While a child pane is shown, the keys, the mouse and the // animation frames go to it (see updateChildView). Every other message // belongs to the parent agent: it is handled by update with the parent pane // shown for the duration of the call, so the parent's transcript keeps up // while the user views a child. func (m *AppModel) routeUpdate(msg tea.Msg) (tea.Model, tea.Cmd) { var cmd tea.Cmd switch msg := msg.(type) { case app.SubagentRunEvent: cmd = m.applySubagentRunEvent(msg) case streamAppendFlushMsg: if msg.paneID != "" { m.flushChildPane(msg.paneID) break } cmd = m.updateParent(msg) default: if m.childView != nil { if handled, c := m.updateChildView(msg); handled { cmd = c break } } cmd = m.updateParent(msg) if size, ok := msg.(tea.WindowSizeMsg); ok { m.resizeChildPanes(size) } } // A parent dialog (an extension prompt, a password prompt, an overlay) // needs the keyboard, which the child view would keep. Show the parent. if m.childView != nil && m.paneRequest == nil && m.state != stateInput && m.state != stateWorking { m.paneRequest = &paneRequest{} } m.applyPaneRequest() return m, cmd } // updateParent runs update with the parent pane shown. func (m *AppModel) updateParent(msg tea.Msg) tea.Cmd { var cmd tea.Cmd parent := m.parentPane if m.childView == nil || parent == nil { parent = m.conversationPane } m.withPane(parent, func() { _, cmd = m.update(msg) }) return cmd } // resizeChildPanes gives a new terminal width to the child panes. The shown // pane gets its viewport size from the next layout pass. func (m *AppModel) resizeChildPanes(size tea.WindowSizeMsg) { for _, p := range m.childPanes { p.renderer.SetWidth(size.Width) if p.stream != nil { updated, _ := p.stream.Update(size) p.stream, _ = updated.(streamComponentIface) } } } // update is the state machine proper. Callers go through Update, which wraps // this to maintain the frame clock. Job layout updates are handled before // modal input routing so status rows keep the correct height behind dialogs. func (m *AppModel) update(msg tea.Msg) (tea.Model, tea.Cmd) { var cmds []tea.Cmd // Stamp the turn clock on entry to / exit from the working state, so the // activity row can report elapsed time without every transition site // having to remember to do it. Deferred so it observes the state as it // stands after this Update has run. // // Keyed on agentWorking() rather than the raw state so that entering and // leaving message navigation — which suspends stateWorking without // stopping the agent — does not report a phantom turn end and restart. workingBefore := m.agentWorking() defer func() { workingAfter := m.agentWorking() if workingAfter && !workingBefore { m.turnStartedAt = time.Now() m.turnToolCount = 0 m.notifyTurnState("working", "idle") } else if !workingAfter && workingBefore { m.turnStartedAt = time.Time{} m.notifyTurnState("idle", "working") } }() // Coalesced streaming: chunk events are buffered and applied on a ~16ms // flush tick instead of per chunk (a full markdown re-render per chunk is // O(n²) over a long response). Any OTHER message flushes the buffer first // so ordering-sensitive handlers (tool calls, reasoning completion, …) // always see fully applied content. This runs before the modal-state // routing below so buffered content never stalls behind a prompt/overlay. switch msg := msg.(type) { case app.StreamChunkEvent, app.ReasoningChunkEvent: // Buffered by the handlers in the main switch below. case streamAppendFlushMsg: m.streamFlushPending = false m.flushPendingStreamChunks() return m, nil case frameTickMsg: // Handled here, ahead of the modal routing below, because a prompt or // overlay opening mid-animation would otherwise swallow the beat and // strand every animation on screen — the wordmark with a highlight // band frozen across it, the activity dot mid-bounce. return m, m.advanceFrame(msg) case app.JobsUpdatedEvent: // Job status changes affect height even while a prompt or overlay // owns input. Invalidate layout before modal routing can consume it. m.layoutDirty = true return m, nil case app.MCPToolsReadyEvent: // Handled here, ahead of the modal routing below, because the end of // MCP loading arrives only once: a prompt or overlay open at that // moment would swallow it, and the tool list and OnMCPToolsReady // would never catch up. Refresh tool names, count, and prompts. m.refreshToolNames() m.refreshMCPToolCount() m.refreshMCPPrompts() // Extension handlers may print, so they run off the Update goroutine. m.extEvents.dispatch(m.emitMCPToolsReady) return m, nil case tea.KeyPressMsg: // Typing into the composer does not read the scrollback, so it // leaves buffered chunks for the scheduled flush tick. Flushing // here forced a full re-render of the streaming message on every // key press, which on a long response made typing lag. if !m.isComposerTextKey(msg) { m.flushPendingStreamChunks() } default: m.flushPendingStreamChunks() } if _, ok := msg.(attachmentPreviewReadyMsg); ok && m.imagePreview == nil { return m, nil } var previewCleanup tea.Cmd if m.imagePreview != nil { switch msg := msg.(type) { case tea.KeyPressMsg: if msg.String() == "ctrl+c" { previewCleanup = tea.Raw(imagepreview.DeleteImage(m.imagePreview.imageID)) m.imagePreview = nil } else { return m.updateImagePreview(msg) } case attachmentPreviewReadyMsg, tea.WindowSizeMsg, tea.MouseClickMsg, tea.MouseWheelMsg, tea.MouseMotionMsg, tea.MouseReleaseMsg: return m.updateImagePreview(msg) } } // An open sheet owns the keyboard and mouse. if m.sheet != nil { if handled, cmd := m.updateSheet(msg); handled { return m, tea.Batch(append(cmds, previewCleanup, cmd)...) } } if kp, ok := msg.(tea.KeyPressMsg); ok && key.Matches(kp, keys.PreviewImages) && !m.modalActive() { if m.input != nil { if in, ok := m.input.(*InputComponent); ok && len(in.pendingImages) > 0 { return m, m.openImagePreview(0) } } } // Prompt overlay takes precedence when active — it is fully modal. if m.state == statePrompt && m.prompt != nil { return m.updatePromptState(msg) } // Overlay dialog takes precedence when active — it is fully modal. if m.state == stateOverlay && m.overlay != nil { return m.updateOverlayState(msg) } switch msg := msg.(type) { // ── Tree selector events ───────────────────────────────────────────────── case uicore.TreeNodeSelectedMsg: // User selected a node in the tree. Branch to it and return to input. if _, ok := m.appCtrl.SessionSnapshot(); ok { // For user messages: branch to parent (so user can resubmit). // For other entries: branch directly to the selected entry. targetID := msg.ID if msg.IsUser { // Branch to parent of user message, place text in editor. targetID = msg.ParentID } // Emit before-fork event in a goroutine so that extension handlers // can call blocking operations (e.g. ctx.PromptConfirm) without // deadlocking the BubbleTea event loop. if m.emitBeforeFork != nil { emit := m.emitBeforeFork ctrl := m.appCtrl forkTargetID := targetID forkIsUser := msg.IsUser forkUserText := msg.UserText go func() { cancelled, reason := emit(forkTargetID, forkIsUser, forkUserText) ctrl.SendUIMessage(beforeForkResultMsg{ cancelled: cancelled, reason: reason, targetID: forkTargetID, isUser: forkIsUser, userText: forkUserText, }) }() m.treeSelector = nil m.state = stateInput return m, noopCmd } cmds = append(cmds, m.performFork(targetID, msg.IsUser, msg.UserText)) } m.treeSelector = nil m.state = stateInput return m, tea.Batch(cmds...) case uicore.TreeCancelledMsg: m.treeSelector = nil m.state = stateInput return m, nil // ── Model selector events ──────────────────────────────────────────────── case ModelSelectedMsg: m.modelSelector = nil m.state = stateInput if m.setModel != nil { m.switchModel(msg.ModelString) } return m, tea.Batch(cmds...) case ModelSelectorCancelledMsg: m.modelSelector = nil m.state = stateInput return m, nil // ── Thinking-level selector events ────────────────────────────────── case ThinkingLevelSelectedMsg: m.thinkingLevelSelector = nil m.state = stateInput m.applyThinkingLevel(models.ParseThinkingLevel(msg.Level)) return m, tea.Batch(cmds...) case ThinkingLevelSelectorCancelledMsg: m.thinkingLevelSelector = nil m.state = stateInput return m, nil case ModelModeSelectedMsg: m.modelModeSelector = nil m.state = stateInput return m, m.applyModelMode(msg.Mode) case modelModeUpdateMsg: if msg.Err != nil { m.printSystemMessage(fmt.Sprintf("Could not set model mode: %v", msg.Err)) return m, nil } m.modelMode = msg.Mode label := msg.Mode if label == "" { label = "Default" } m.printSystemMessage("Model mode set to: " + label) return m, nil case ModelModeSelectorCancelledMsg: m.modelModeSelector = nil m.state = stateInput return m, nil // ── Kill-subagent selector events ─────────────────────────────────── // The state is not changed here: the picker does not own an appState. case KillSubagentSelectedMsg: m.killSubagentSelector = nil m.killSubagent(msg.ID, msg.Label) return m, tea.Batch(cmds...) case KillSubagentSelectorCancelledMsg: m.killSubagentSelector = nil return m, nil case SubagentRunSelectedMsg, SubagentRunPickerCancelledMsg: return m, m.updateSubagentRunPickerEvent(msg) // ── Theme selector events ─────────────────────────────────────────────── case ThemeSelectedMsg: m.themeSelector = nil m.state = stateInput m.applyTheme(msg.Name) return m, tea.Batch(cmds...) case ThemeSelectorCancelledMsg: m.themeSelector = nil m.state = stateInput return m, nil // ── Provider connect (/connect) events ───────────────────────────────── case ProviderKeySubmittedMsg: if err := m.storeProviderKey(msg.ProviderID, msg.Key); err != nil { // Keep the dialog open on the key step so the user can fix it. if m.providerConnect != nil { m.providerConnect.SetError(err.Error()) } return m, nil } m.providerConnect = nil m.state = stateInput m.afterProviderKeySaved(msg.ProviderID, msg.ProviderName) return m, tea.Batch(cmds...) case ProviderConnectOAuthMsg: m.providerConnect = nil m.state = stateInput m.printSystemMessage(fmt.Sprintf( "%s uses device login instead of an API key. Quit and run:\n\n kit auth login copilot", msg.ProviderName)) return m, tea.Batch(cmds...) case ProviderConnectCancelledMsg: m.providerConnect = nil m.state = stateInput return m, nil // ── Session selector events ────────────────────────────────────────────── case SessionSelectedMsg: m.sessionSelector = nil m.state = stateInput if m.switchSession != nil { if err := m.switchSession(msg.Path); err != nil { m.printSystemMessage(fmt.Sprintf("Failed to switch session: %v", err)) } else { m.renderSessionHistory() m.printSystemMessage("Session loaded. Continue where you left off.") } } else { m.printSystemMessage("Session switching not available.") } // The provider may still be unusable (e.g. a failed OAuth refresh); // surface the selector now that the session picker is out of the way. m.openModelSelectorForProviderError() return m, tea.Batch(cmds...) case SessionSelectorCancelledMsg: m.sessionSelector = nil m.state = stateInput m.openModelSelectorForProviderError() return m, nil case SessionDeletedMsg: // Session was deleted from picker — just show a message. m.printSystemMessage(fmt.Sprintf("Deleted session: %s", msg.Name)) return m, tea.Batch(cmds...) // ── Window resize ──────────────────────────────────────────────────────── case tea.WindowSizeMsg: m.width = msg.Width m.height = msg.Height m.layoutDirty = true if m.imagePreview != nil { cmds = append(cmds, tea.Sequence(tea.Raw(imagepreview.DeleteImage(m.imagePreview.imageID)), m.openImagePreview(m.imagePreview.index))) } m.notifyResize() // Update renderer width for proper message styling m.renderer.SetWidth(m.width) // Propagate to children. if m.input != nil { updated, cmd := m.input.Update(msg) m.input, _ = updated.(inputComponentIface) cmds = append(cmds, cmd) } if m.stream != nil { updated, cmd := m.stream.Update(msg) m.stream, _ = updated.(streamComponentIface) cmds = append(cmds, cmd) } if m.killSubagentSelector != nil { m.killSubagentSelector.Update(msg) } // A width change re-wraps every message, so the selected one can end // up outside the viewport. Pull it back into view rather than leaving // the user navigating a selection they cannot see. // // The layout pass has to run first: SetWidth/SetHeight land in // distributeHeight, which View() defers until the next frame. Choosing // an offset before that would measure the selected item at the old // width (and against a stale viewport height), so a message that grew // taller under the new wrapping could still end up clipped. // // layoutDirty is deliberately left set so View() still runs its own // pass and repopulates the chrome cache it invalidates each frame. // The repeat is cheap — SetWidth is a no-op at an unchanged width. if m.state == stateMessageNav && m.scrollList != nil { m.distributeHeight() m.scrollList.EnsureVisible(m.scrollList.SelectedIndex()) } // ── Mouse wheel scrolling ──────────────────────────────────────────────── case tea.MouseWheelMsg: if _, height := m.currentScrollbackBounds(); height <= 0 { break } // Scroll the scrollback viewport with mouse wheel const scrollLines = 3 switch msg.Button { case tea.MouseWheelUp: m.scrollList.ScrollBy(-scrollLines) m.scrollList.autoScroll = false case tea.MouseWheelDown: m.scrollList.ScrollBy(scrollLines) // Only re-enable auto-scroll when the user is not actively // selecting text. Otherwise a wheel-down during a drag-select // would re-arm GotoBottom on the next stream chunk, shifting // the highlighted row out from under the cursor. if m.scrollList.AtBottom() && !m.scrollList.IsMouseDown() { m.scrollList.autoScroll = true } } // ── Mouse click selection (crush-style character-level) ────────────────── case tea.MouseClickMsg: if msg.Button == tea.MouseLeft { if in, ok := m.input.(*InputComponent); ok && msg.Y >= m.inputYOffset { if index, remove := in.ImageTileAt(msg.X, msg.Y-m.inputYOffset); index >= 0 { if remove { return m, in.RemoveImage(index) } return m, m.openImagePreview(index) } } // Compute the scrollback origin from the current frame's layout // rather than the stale cached value from the previous View(). // scrollbackYOffset/scrollList.height are only refreshed inside // View() and lag behind any state change that resized the header // (extension widgets, warning rows, etc.) since the last render. yOff, vpHeight := m.currentScrollbackBounds() viewY := msg.Y - yOff if viewY >= 0 && viewY < vpHeight { // Clear any previous selection on a new click. // HandleMouseDown will set up new selection state. if m.scrollList.HandleMouseDown(msg.X, viewY) { m.scrollList.autoScroll = false } } } // ── Mouse motion/drag for character-level selection ────────────────────── case tea.MouseMotionMsg: yOff, vpHeight := m.currentScrollbackBounds() viewY := msg.Y - yOff if viewY >= 0 && viewY < vpHeight { m.scrollList.HandleMouseDrag(msg.X, viewY) } // ── Mouse release: finalize selection and copy to clipboard ────────────── case tea.MouseReleaseMsg: if m.scrollList.HandleMouseUp() { // Selection completed — extract text and copy to clipboard. text := m.scrollList.ExtractSelectedText() if text == "" { m.scrollList.ClearSelection() } else { cmds = append(cmds, clipboard.CopySelection(text)) m.clipboardFailed = false // The selection stays highlighted, so the user can see // what was copied, and the status bar says how much. In // message navigation, the navigation notice says it. m.scrollList.KeepSelection(text) if m.state == stateMessageNav { m.navCopied = len([]rune(text)) m.navNotice = fmt.Sprintf("Copied %d chars to clipboard.", m.navCopied) } } } // ── Keyboard input ─────────────────────────────────────────────────────── case tea.KeyPressMsg: return m.handleKeyPress(msg, cmds, previewCleanup) // ── Cancel timer expired ───────────────────────────────────────────────── case uicore.CancelTimerExpiredMsg: if m.canceling { m.layoutDirty = true } m.canceling = false // ── Ctrl+C reset timer expired ──────────────────────────────────────────── case uicore.CtrlCResetMsg: if m.ctrlCPressedOnce { m.layoutDirty = true } m.ctrlCPressedOnce = false // ── Input submitted ────────────────────────────────────────────────────── case uicore.SubmitMsg: return m.handleSubmit(msg, cmds) // ── Async transcript image preview ─────────────────────────────────────── case imagePreviewReadyMsg: return m.handleImagePreviewReady(msg, cmds) // ── Shell command (! / !!) ─────────────────────────────────────────────── case uicore.ShellCommandMsg: // Show spinner while the shell command runs. m.setAgentState(stateWorking) if m.stream != nil { updated, cmd := m.stream.Update(app.SpinnerEvent{Show: true}) m.stream, _ = updated.(streamComponentIface) cmds = append(cmds, cmd) } // Execute the shell command asynchronously so the TUI stays responsive. cmds = append(cmds, m.executeShellCommand(msg)) case uicore.ShellStreamChunkMsg: cmds = append(cmds, m.handleShellCommandChunk(msg)) case uicore.ShellCommandResultMsg: // Stop spinner now that the command has finished. if m.stream != nil { updated, cmd := m.stream.Update(app.SpinnerEvent{Show: false}) m.stream, _ = updated.(streamComponentIface) cmds = append(cmds, cmd) } m.setAgentState(stateInput) cmds = append(cmds, m.handleShellCommandResult(msg)) default: return m.handleAppMessage(msg, cmds) } return m, tea.Batch(cmds...) } // View implements tea.Model. It renders the stacked layout: // stream region + separator + [queued messages] + [activity row] + input // region + status bar. The status bar is always present (1 line) to avoid // layout shifts; the activity row appears only while the agent is working. // When the tree selector is active, it replaces the stream region. func (m *AppModel) View() tea.View { // When quitting, disable alt screen for clean terminal restoration. // This prevents terminal corruption issues on exit. if m.quitting { v := tea.NewView("") v.AltScreen = false v.MouseMode = tea.MouseModeNone return v } // Tree selector, session selector and the overlay dialog are composited // over the normal layout further down, alongside the slash popup and the // model selector, so every modal in the app shows the conversation // behind it instead of blanking the screen. // Recompute layout heights if any Update() changed state that affects // sizing. Deferring this to View() guarantees exactly one call per frame // regardless of how many events triggered a layout change in a single // Update() invocation. // // The chrome cache is never reused across frames: it is invalidated here // and only repopulated by the distributeHeight() call below, so a stale // render can never leak into a later frame. m.chrome.valid = false m.renderEpoch++ m.syncActivityRow() m.syncSubagentStatusBar() if m.layoutDirty || m.fillActive { m.distributeHeight() m.layoutDirty = false } // After layout is recalculated with correct heights, scroll to bottom // if requested (e.g. after loading a session). if m.pendingGotoBottom { m.scrollList.GotoBottom() m.pendingGotoBottom = false } vis := m.uiVis() // Render scrollback content from ScrollList (replaces renderStream() in alt screen mode) scrollbackView := m.renderScrollback() // When a prompt is active, it replaces the input area for consistency // (appears below the separator, in the same position as the input). var inputView string if m.chrome.valid { inputView = m.chrome.input } else if m.state == statePrompt && m.prompt != nil { inputView = m.prompt.Render() } else { inputView = m.renderInput() } // Build the stacked layout. Optional header/footer wrap the core layout. var parts []string // Custom header (if set by extension) — above everything. // Track its height so mouse coordinates can be adjusted for the scrollback. m.scrollbackYOffset = 0 headerView := m.chrome.header if !m.chrome.valid { headerView = m.renderHeaderFooter("header", m.getHeader) } if headerView != "" { parts = append(parts, headerView) m.scrollbackYOffset = lipgloss.Height(headerView) } // Keep the mouse-handler view of the header height in sync with what // was actually rendered this frame. m.lastHeaderHeight = m.scrollbackYOffset // Only include the scrollback region when it has content. When idle the // scrollback renders "" which JoinVertical would pad to a full-width blank // line, inflating the view unnecessarily. // // Its index is kept because a directly-placed transcript image is located // relative to the top of this section. scrollPartIndex := -1 if scrollbackView != "" { scrollPartIndex = len(parts) parts = append(parts, scrollbackView) } // Confirmation prompts for destructive keys live in the activity row while // the agent is working, since that row is already showing the interrupt // affordance and is where the eye is. When idle there is no activity row, // so the prompt gets its own line here instead. theme := style.GetTheme() if m.ctrlCPressedOnce && !m.agentWorking() { warning := lipgloss.NewStyle(). Foreground(theme.Warning). Render(strings.Repeat(" ", style.ContentOffset) + "ctrl+c again to quit") parts = append(parts, warning) } if !vis.HideSeparator { // The separator only materialises when it has something to say, so // an idle screen carries no rule between transcript and composer. if sep := m.renderSeparator(); sep != "" { parts = append(parts, sep) } } // Render "above" widgets between separator and queued messages. aboveView := m.chrome.above if !m.chrome.valid { aboveView = m.renderWidgetSlot("above") } if aboveView != "" { parts = append(parts, aboveView) } queuedView := m.chrome.queued if !m.chrome.valid { queuedView = m.renderQueuedMessages() } if queuedView != "" { parts = append(parts, queuedView) } // Live activity sits immediately above the composer so the eye finds it // in the same place it is about to type. It costs zero lines when idle. activityView := m.chrome.activity if !m.chrome.valid { activityView = m.renderActivityRow() } subagentView := m.chrome.subagents if !m.chrome.valid { subagentView = m.renderBackgroundStatus() } if subagentView != "" { parts = append(parts, subagentView) } if activityView != "" { parts = append(parts, activityView) } inputPartIndex := len(parts) parts = append(parts, inputView) // Render "below" widgets between input and status bar. belowView := m.chrome.below if !m.chrome.valid { belowView = m.renderWidgetSlot("below") } if belowView != "" { parts = append(parts, belowView) } if !vis.HideStatusBar { parts = append(parts, m.renderStatusBar()) } // Custom footer (if set by extension) — below everything. footerView := m.chrome.footer if !m.chrome.valid { footerView = m.renderHeaderFooter("footer", m.getFooter) } if footerView != "" { parts = append(parts, footerView) } m.inputYOffset = m.height - lipgloss.Height(inputView) for _, part := range parts[inputPartIndex+1:] { m.inputYOffset -= lipgloss.Height(part) } content := lipgloss.JoinVertical(lipgloss.Left, parts...) // Record where directly-placed images landed. This must happen with the // assembled parts in hand: the absolute screen row of a preview is only // knowable once everything above and below it has been measured. placement := m.computeGfxPlacement(parts, inputPartIndex, scrollPartIndex) if placement != m.gfxPlacement { m.gfxDirty = true } m.gfxPlacement = placement // Composite every modal surface over the layout at the cell level, so // the conversation stays visible around each one. Ordering is z-order: // later draws sit on top. finalContent := content // Slash / @ autocomplete popup. if ic, ok := m.input.(*InputComponent); ok { if box := ic.RenderPopupBox(m.width, m.height); box != "" { finalContent = compositeCentered(finalContent, box, m.width, m.height) } } // Model selector. if m.state == stateModelSelector && m.modelSelector != nil { finalContent = compositeCentered(finalContent, m.modelSelector.RenderOverlay(), m.width, m.height) } // Thinking-level selector. if m.state == stateThinkingLevelSelector && m.thinkingLevelSelector != nil { finalContent = compositeCentered(finalContent, m.thinkingLevelSelector.RenderOverlay(), m.width, m.height) } if m.state == stateModelModeSelector && m.modelModeSelector != nil { finalContent = compositeCentered(finalContent, m.modelModeSelector.RenderOverlay(), m.width, m.height) } // Kill-subagent selector. if m.killSubagentOpen() { finalContent = compositeCentered(finalContent, m.killSubagentSelector.RenderOverlay(), m.width, m.height) } if m.subagentRunPickerOpen() { finalContent = compositeCentered(finalContent, m.subagentRunPicker.RenderOverlay(), m.width, m.height) } // Theme selector. if m.state == stateThemeSelector && m.themeSelector != nil { finalContent = compositeCentered(finalContent, m.themeSelector.RenderOverlay(), m.width, m.height) } // Provider connect dialog (/connect). if m.state == stateProviderConnect && m.providerConnect != nil { finalContent = compositeCentered(finalContent, m.providerConnect.RenderOverlay(), m.width, m.height) } // Tree selector (/tree). if m.state == stateTreeSelector && m.treeSelector != nil { finalContent = compositeCentered(finalContent, m.treeSelector.RenderOverlay(), m.width, m.height) } // Session selector (/resume). if m.state == stateSessionSelector && m.sessionSelector != nil { finalContent = compositeCentered(finalContent, m.sessionSelector.RenderOverlay(), m.width, m.height) } // Modal dialog — extension overlays and the message inspector. Honours // the caller's vertical anchor. if m.state == stateOverlay && m.overlay != nil { finalContent = compositeAnchored(finalContent, m.overlay.Render(), m.overlay.Anchor(), m.width, m.height) } if m.imagePreview != nil { finalContent = compositeCentered(finalContent, m.renderImagePreview(), m.width, m.height) } if m.sheet != nil { finalContent = compositeCentered(finalContent, m.renderSheet(), m.width, m.height) } // Notice a repaint. The renderer scrolls the screen to update it, and a // terminal scrolls its images along with the text, so any change to the // frame can move an image that is not part of the frame. Hashing the // content is how a directly-placed image learns it must be drawn again. h := fnv.New64a() _, _ = h.Write([]byte(finalContent)) if sum := h.Sum64(); sum != m.gfxContentHash { m.gfxContentHash = sum // Only a frame that still shows an image needs one drawn. The hash is // updated either way, so that a frame rendered while no image was // attached cannot later be mistaken for an unchanged screen. m.gfxDirty = m.gfxDirty || m.gfxPlacement != "" } v := tea.NewView(finalContent) v.AltScreen = true v.MouseMode = tea.MouseModeCellMotion v.ReportFocus = true v.KeyboardEnhancements = tea.KeyboardEnhancements{ ReportEventTypes: true, } return v } // -------------------------------------------------------------------------- // Rendering helpers // -------------------------------------------------------------------------- // refreshContent updates the ScrollList with current messages. // Called whenever messages change (new message, streaming update, etc.) // ScrollList lazily renders only visible items on View() call. func (m *AppModel) refreshContent() { if m.scrollList == nil { return } // SetItems handles autoscroll internally if enabled m.scrollList.SetItems(m.messages) } // renderScrollback returns the scrollback content from ScrollList. // This replaces renderStream() in alt screen mode. func (m *AppModel) renderScrollback() string { // Content is refreshed via refreshContent() when messages change // ScrollList renders lazily on View() call return m.scrollList.View() } // renderStatusBar renders a persistent single-line status bar below the input. // Left side: spinner (when active). Middle: extension status entries (sorted by // priority). Right side: provider · model + usage stats. // This bar is always present so its height is constant, eliminating layout // shifts from spinner or usage info appearing/disappearing. // renderStatusBar renders the ambient footer: a single muted line carrying // context that is true regardless of what the agent is doing. // // ~/Workspace/kit (master) anthropic · claude-opus-5 · 7.2K · $0.02 // // Live activity deliberately does not appear here — it owns the activity row // directly above the composer (see renderActivityRow). Keeping the two apart // means a long-running command can never be squeezed out by a token counter. func (m *AppModel) renderStatusBar() string { theme := style.GetTheme() muted := lipgloss.NewStyle().Foreground(theme.Muted) veryMuted := lipgloss.NewStyle().Foreground(theme.VeryMuted) // Left: working directory, plus the git branch when one is known. // While message navigation owns the keyboard its key hints take that // slot instead: the rebound keys are transient and need discovering, // whereas the path is ambient and always recoverable by pressing Esc. // // The mode label stays up while the inspector is open, because Esc there // returns to navigation rather than leaving it. Its key hints do not: the // dialog carries its own, and showing both would advertise two sets of // bindings for one keyboard. var leftSide string var hasNotice bool // the left side answers something the user just did if m.navActive() { var trailing string switch { case m.state != stateMessageNav: // A modal opened from navigation owns the keyboard and the hints. case m.navNotice != "": // A notice displaces the key hints rather than crowding in beside // them: it is transient and answers something the user just did, // whereas the hints are always one Esc away from being needed. notice := lipgloss.NewStyle().Foreground(theme.Success).Render(m.navNotice) if m.navCopied > 0 { notice = m.copyNotice(m.navCopied) } trailing = " " + notice hasNotice = true default: trailing = veryMuted.Render(" ↑/↓ move · u/U user · y copy · enter open · esc exit") } leftSide = " " + lipgloss.NewStyle(). Foreground(theme.Accent). Render("MESSAGE NAV") + trailing } else if n := m.scrollList.CopiedChars(); n > 0 { // Like the navigation notice, the copy notice displaces the path, // for as long as the copied selection stays highlighted. leftSide = " " + m.copyNotice(n) hasNotice = true } else if m.cwd != "" { left := tildeHome(m.cwd) if m.gitBranch != "" { left += " (" + m.gitBranch + ")" } leftSide = " " + muted.Render(left) } // Extension status entries and the thinking level sit next to the path. // They are ambient facts, not activity. var middleParts []string if m.isReasoningModel && m.thinkingLevel != "" && m.thinkingLevel != "off" { middleParts = append(middleParts, veryMuted.Render("thinking: "+m.thinkingLevel)) } if m.modelMode != "" { middleParts = append(middleParts, veryMuted.Render("mode: "+m.modelMode)) } if m.getStatusBarEntries != nil { for _, e := range m.getStatusBarEntries() { middleParts = append(middleParts, veryMuted.Render(e.Text)) } } middleSide := strings.Join(middleParts, veryMuted.Render(" · ")) if middleSide != "" && leftSide != "" { middleSide = veryMuted.Render(" · ") + middleSide } // Right: provider, model, then usage. Ordered least-important-first so // progressive truncation drops cost before it drops the model name. var rightParts []string if m.providerName != "" && m.modelName != "" { rightParts = append(rightParts, muted.Render(m.providerName+" · "+m.modelName)) } else if m.modelName != "" { rightParts = append(rightParts, muted.Render(m.modelName)) } if m.usageTracker != nil { if usage := m.usageTracker.RenderUsageInfo(); usage != "" { rightParts = append(rightParts, usage) } } sep := veryMuted.Render(" · ") rightSide := strings.Join(rightParts, sep) // Progressive truncation, in order: extension/thinking entries, then // usage, then the model label, then the path. fits := func(l, mid, r string) bool { return lipgloss.Width(l)+lipgloss.Width(mid)+lipgloss.Width(r)+1 <= m.width } if !fits(leftSide, middleSide, rightSide) { middleSide = "" } if !fits(leftSide, middleSide, rightSide) && len(rightParts) > 1 { rightParts = rightParts[:len(rightParts)-1] rightSide = strings.Join(rightParts, sep) } // A notice on the left outlasts the model label, where the notice fits // on its own: it is transient and answers something the user just did. if hasNotice && !fits(leftSide, middleSide, rightSide) && fits(leftSide, middleSide, "") { rightSide = "" } if !fits(leftSide, middleSide, rightSide) { leftSide = "" } if !fits(leftSide, middleSide, rightSide) { rightSide = "" } gap := max(m.width-lipgloss.Width(leftSide)-lipgloss.Width(middleSide)-lipgloss.Width(rightSide), 1) return leftSide + middleSide + strings.Repeat(" ", gap) + rightSide } // copyNotice renders the status bar acknowledgement for a copy of n // characters, as a warning when the copy did not reach the system clipboard. func (m *AppModel) copyNotice(n int) string { theme := style.GetTheme() if m.clipboardFailed { return lipgloss.NewStyle().Foreground(theme.Warning). Render(fmt.Sprintf("Copied %d chars; system clipboard failed.", n)) } return lipgloss.NewStyle().Foreground(theme.Success). Render(fmt.Sprintf("Copied %d chars to clipboard.", n)) } // cycleThinkingLevel advances to the next thinking level and applies it. func (m *AppModel) cycleThinkingLevel() { supported := models.SupportedThinkingLevels(m.providerName, m.modelName) levels := make([]string, len(supported)) for i, level := range supported { levels[i] = string(level) } current := m.thinkingLevel if current == "" { current = "off" } // Find current index and advance to next. idx := 0 for i, l := range levels { if l == current { idx = i break } } next := levels[(idx+1)%len(levels)] m.thinkingLevel = next // Apply the change to the agent/provider. if m.setThinkingLevel != nil { // Run in goroutine to avoid blocking the event loop (provider // recreation may take time). go func() { // ThinkingLevelChangeEvent.NewLevel promises the level now in // effect, so announce only once the provider has accepted it. if err := m.setThinkingLevel(next); err == nil { m.notifyThinkingLevel(next, current, "user") } }() } else { m.notifyThinkingLevel(next, current, "user") } // Persist thinking level for next launch. go func() { _ = prefs.SaveThinkingLevelPreference(next) }() } // renderSeparator renders the queue/steer announcement shown between the // transcript and the composer. // // There is deliberately no full-width rule here. The transcript and the // composer are already separated by the composer's own filled background and // by whitespace; drawing a horizontal line as well was the single heaviest // element on screen and carried no information. When there is nothing queued // or steering, this returns "" and costs no vertical space. func (m *AppModel) renderSeparator() string { queueLen := len(m.queuedMessages) steerLen := len(m.steeringMessages) if steerLen == 0 && queueLen == 0 { return "" } theme := style.GetTheme() var parts []string if steerLen > 0 { parts = append(parts, lipgloss.NewStyle(). Foreground(theme.Warning). Render(fmt.Sprintf("%d steering", steerLen))) } if queueLen > 0 { parts = append(parts, lipgloss.NewStyle(). Foreground(theme.Secondary). Render(fmt.Sprintf("%d queued", queueLen))) } badge := strings.Join(parts, " ") // Right-align the badge so it reads as chrome rather than as content. pad := max(m.width-lipgloss.Width(badge)-1, 1) return strings.Repeat(" ", pad) + badge } // renderInput returns the input region content. If an editor interceptor // is active and provides a Render function, the default content is passed // through it for wrapping/modification. func (m *AppModel) renderInput() string { if m.childView != nil && m.child != nil { return m.renderChildBar() } if m.input == nil { return "" } content := m.input.View().Content if m.getEditorInterceptor != nil { if interceptor := m.getEditorInterceptor(); interceptor != nil && interceptor.Render != nil { content = interceptor.Render(m.width, content) } } return content } // renderWidgetSlot renders all extension widgets for the given placement // ("above" or "below"). Returns "" if no widgets exist for that slot. func (m *AppModel) renderWidgetSlot(placement string) string { if m.getWidgets == nil { return "" } widgets := m.getWidgets(placement) if len(widgets) == 0 { return "" } return m.renderWidgets(placement, widgets, nil) } // renderWidgets skips fill widgets during measurement (nil heights). The final // pass uses the same widget snapshot and assigned heights as distributeHeight. func (m *AppModel) renderWidgets(placement string, widgets []WidgetData, heights map[string]int) string { theme := style.GetTheme() var blocks []string for _, w := range widgets { key := placement + ":" + w.ID height := -1 // natural height if w.FillHeight { if heights == nil || heights[key] <= 0 { continue } height = heights[key] } content, ok := m.resolveWidgetContentSized(w, key, m.width, height) if !ok { continue } var opts []renderingOption opts = append(opts, WithAlign(lipgloss.Left)) if w.NoBorder { opts = append(opts, WithNoBorder()) } else { borderClr := theme.Accent if w.BorderColor != "" { borderClr = lipgloss.Color(w.BorderColor) } opts = append(opts, WithBorderColor(borderClr)) } // Use tighter padding for widgets (less vertical padding than // full message blocks) so they feel compact and unobtrusive. opts = append(opts, WithPaddingTop(0), WithPaddingBottom(0)) block := renderContentBlock(content, m.width, opts...) if height >= 0 { // Enforce after styling too: wrapping and trimmed trailing newlines // must not change the number of allocated rows. block = fitWidgetHeight(block, height) } blocks = append(blocks, block) } return strings.Join(blocks, "\n") } // renderHeaderFooter renders a custom header or footer from an extension. The // getter function returns the current data (*WidgetData) or nil when inactive. // Returns "" when the getter is nil or returns nil. Uses the same rendering // pipeline as widgets for visual consistency. func (m *AppModel) renderHeaderFooter(slot string, getter func() *WidgetData) string { if getter == nil { return "" } data := getter() if data == nil { return "" } theme := style.GetTheme() content, ok := m.resolveWidgetContent(*data, slot, m.width) if !ok { return "" } var opts []renderingOption opts = append(opts, WithAlign(lipgloss.Left)) if data.NoBorder { opts = append(opts, WithNoBorder()) } else { borderClr := theme.Accent if data.BorderColor != "" { borderClr = lipgloss.Color(data.BorderColor) } opts = append(opts, WithBorderColor(borderClr)) } // Compact padding like widgets. opts = append(opts, WithPaddingTop(0), WithPaddingBottom(0)) return renderContentBlock(content, m.width, opts...) } // widgetContentWidth returns the number of columns available to widget content // once the block's gutter glyph and horizontal padding are subtracted. This is // the width handed to a WidgetData.Render callback, so extensions can size // their own output to the exact column they will be drawn into. func widgetContentWidth(containerWidth int, noBorder bool) int { borderChars := 1 if noBorder { borderChars = 0 } return containerWidth - borderChars - (style.ContentOffset - 1) - style.RightMargin } // widgetFrameDivisor maps a requested repaint rate to a number of shared-clock // frames. The clock runs at a fixed FrameClockFPS, so a widget that wants less // than that subdivides it, exactly as the activity spinner does. func widgetFrameDivisor(hz int) int { if hz <= 0 || hz >= FrameClockFPS { return 1 } return FrameClockFPS / hz } // animatedWidgets reports whether any extension widget, header or footer has // asked for continuous repaints. It is what lets an extension keep the shared // animation clock alive; see wantsFrames. func (m *AppModel) animatedWidgets() bool { if m.getWidgets != nil { for _, placement := range []string{"above", "below"} { for _, w := range m.getWidgets(placement) { if (w.Render != nil || (w.FillHeight && w.RenderSized != nil)) && w.RefreshHz > 0 { return true } } } } for _, get := range []func() *WidgetData{m.getHeader, m.getFooter} { if get == nil { continue } if d := get(); d != nil && d.Render != nil && d.RefreshHz > 0 { return true } } return false } // resolveWidgetContent produces the body for a widget, header or footer slot. // // A Render callback wins over Text and its output is used verbatim, which is // what lets an extension draw arbitrary UI. Text is styled as markdown only // when asked for. The bool result is false when the slot should be skipped // entirely (empty content, or a width too small to draw into). // // key identifies the slot for the animation render cache. Every View() pass // invalidates the chrome cache, so without this an animated widget would // re-enter the interpreter on every one of the 30 frames a second the clock // ticks at. Gating on the widget's own rate keeps that crossing proportional // to what it actually asked for. func (m *AppModel) resolveWidgetContent(w WidgetData, key string, containerWidth int) (string, bool) { return m.resolveWidgetContentSized(w, key, containerWidth, -1) } // resolveWidgetContentSized renders natural content at height -1 or fits the // body to the allocated fill rows, with dimensions included in cache lookup. func (m *AppModel) resolveWidgetContentSized(w WidgetData, key string, containerWidth, height int) (string, bool) { width := widgetContentWidth(containerWidth, w.NoBorder) if height == 0 { return "", false } if height > 0 { if width < 1 { return "", false } if cached, ok := m.cachedWidgetRender(w, key, width, height); ok { return cached, true } var content string switch { case w.RenderSized != nil: content = safeWidgetRender(func(width int) string { return w.RenderSized(width, height) }, width) case w.Render != nil: content = safeWidgetRender(w.Render, width) case w.Markdown: content = widgetMarkdown(w.Text, containerWidth, w.NoBorder) default: content = w.Text } content = fitWidgetHeight(content, height) m.storeWidgetRender(w, key, width, height, content) return content, true } if w.Render != nil { if width < 1 { return "", false } if cached, ok := m.cachedWidgetRender(w, key, width, height); ok { if cached == "" { return "", false } return cached, true } // Extension code runs here. A panic in a widget must not take down the // TUI, so it degrades to a hidden widget. content := safeWidgetRender(w.Render, width) m.storeWidgetRender(w, key, width, height, content) if content == "" { return "", false } return content, true } if w.Text == "" { return "", false } if w.Markdown { return widgetMarkdown(w.Text, containerWidth, w.NoBorder), true } return w.Text, true } // widgetBeat returns the cache generation for a widget's Render output. // // An animated widget advances on its own subdivision of the shared clock, so // its Render is entered at the rate it asked for rather than on every frame. // A static widget uses the current View() pass, which caches nothing across // frames but does guarantee the measure and paint passes agree. func (m *AppModel) widgetBeat(w WidgetData) int { if w.RefreshHz > 0 { return m.frames.frame / widgetFrameDivisor(w.RefreshHz) } return m.renderEpoch } // cachedWidgetRender returns a previously rendered body when the widget is not // due to advance. See widgetBeat for what "due" means in each mode. func (m *AppModel) cachedWidgetRender(w WidgetData, key string, width, height int) (string, bool) { if key == "" { return "", false } entry, ok := m.widgetRenders[key] if !ok || entry.width != width || entry.height != height || entry.beat != m.widgetBeat(w) { return "", false } return entry.content, true } // storeWidgetRender records a render for the widget cache. func (m *AppModel) storeWidgetRender(w WidgetData, key string, width, height int, content string) { if key == "" { return } if m.widgetRenders == nil { m.widgetRenders = make(map[string]widgetRenderCache) } m.widgetRenders[key] = widgetRenderCache{ content: content, width: width, height: height, beat: m.widgetBeat(w), } } // fitWidgetHeight returns exactly height rows, including for empty output. func fitWidgetHeight(content string, height int) string { if height <= 0 { return "" } lines := strings.Split(content, "\n") if len(lines) > height { lines = lines[:height] } for len(lines) < height { lines = append(lines, " ") } return strings.Join(lines, "\n") } // safeWidgetRender invokes an extension render callback, converting a panic // into empty output rather than crashing the render loop. func safeWidgetRender(render func(int) string, width int) (out string) { defer func() { if r := recover(); r != nil { log.Error("extension widget render panicked", "error", r) out = "" } }() return render(width) } // widgetMarkdown renders widget/header/footer content as styled markdown, // sized to the text column that renderContentBlock will lay it into. // // The block reserves one column for the gutter glyph (when bordered), plus // the shared left content offset and the right margin; rendering markdown at // the full container width would wrap a second time inside those paddings. func widgetMarkdown(content string, containerWidth int, noBorder bool) string { width := widgetContentWidth(containerWidth, noBorder) if width < 1 { return content } return strings.TrimSuffix(style.ToMarkdown(content, width), "\n") } // maxQueuedMessageLines is the maximum number of visible content lines // rendered for each queued or steering message block. Messages exceeding // this limit are truncated with an ellipsis to prevent large pastes from // overflowing the screen and squeezing the stream region to zero. const maxQueuedMessageLines = 3 // renderQueuedMessages renders queued and steering prompts as styled content // blocks with badges, anchored between the separator and input. Steering // messages use a distinct "STEERING" badge to differentiate from queued ones. // Long messages are visually truncated to maxQueuedMessageLines. func (m *AppModel) renderQueuedMessages() string { if len(m.queuedMessages) == 0 && len(m.steeringMessages) == 0 { return "" } theme := style.GetTheme() // Available content width inside the block: container minus border (1) // minus left padding (2). Used to estimate line wrapping for truncation. contentWidth := max(m.width-3, 10) var blocks []string // Render steering messages first (higher priority). if len(m.steeringMessages) > 0 { badge := style.CreateBadge("STEERING", theme.Warning) for _, msg := range m.steeringMessages { display := truncateMessageForBlock(msg, maxQueuedMessageLines, contentWidth) content := display + "\n" + badge rendered := renderContentBlock( content, m.width, WithAlign(lipgloss.Left), WithBorderColor(theme.Warning), ) blocks = append(blocks, rendered) } } // Render queued messages. if len(m.queuedMessages) > 0 { badge := style.CreateBadge("QUEUED", theme.Accent) for _, msg := range m.queuedMessages { display := truncateMessageForBlock(msg, maxQueuedMessageLines, contentWidth) content := display + "\n" + badge rendered := renderContentBlock( content, m.width, WithAlign(lipgloss.Left), WithBorderColor(theme.Muted), ) blocks = append(blocks, rendered) } } return strings.Join(blocks, "\n") } // truncateMessageForBlock truncates a message to at most maxLines visible // lines, accounting for soft-wrapping at the given width. If the message is // truncated, the last visible line is replaced with an ellipsis ("…"). func truncateMessageForBlock(msg string, maxLines, width int) string { if width <= 0 { width = 1 } lines := strings.Split(msg, "\n") // Count visible lines (each hard line may wrap into multiple visual lines). var kept []string visibleCount := 0 truncated := false for _, line := range lines { // Calculate how many visual lines this hard line occupies. lineWidth := lipgloss.Width(line) wrapped := 1 if lineWidth > width { wrapped = (lineWidth + width - 1) / width // ceil division } if visibleCount+wrapped > maxLines { // This line would exceed the limit. Keep a partial if we // still have room for at least one more visual line. remaining := maxLines - visibleCount if remaining > 0 { // Truncate the line to fit the remaining visual lines. runes := []rune(line) maxRunes := remaining * width if maxRunes < len(runes) { kept = append(kept, string(runes[:maxRunes])) } else { kept = append(kept, line) } } truncated = true break } kept = append(kept, line) visibleCount += wrapped } if !truncated { return msg } return strings.Join(kept, "\n") + "…" } // -------------------------------------------------------------------------- // Print helpers — add content to ScrollList // -------------------------------------------------------------------------- // imagePreviewReadyMsg carries asynchronously rendered transcript image // previews back to the Update loop, where they are inserted into the // ScrollList directly after the originating user message (identified by // anchorID). Inserting by anchor — rather than appending — keeps the preview // next to its message even when the agent's streamed reply has already been // appended while the thumbnail was being decoded off the event loop. type imagePreviewReadyMsg struct { previews []transcriptPreview anchorID string // transmit carries image data that must reach the terminal outside the // view text, and is empty for half-block previews. See // imagepreview.Thumbnail. transmit string } // transcriptPreview is one rendered thumbnail on its way into the scrollback. // // Each preview becomes its own scrollback item. One item per image is what // makes a directly-placed picture locatable: the item's rows are the image's // rows, so the model can work out where the picture goes from the item's // position alone, with no arithmetic about what else shares the block. type transcriptPreview struct { // cells is the text inserted into the transcript: half-block art, // placeholder cells, or the blank block that reserves the area a directly // placed image is painted over. cells string // image is the transmitted image when it must be placed over the screen, // and nil when the cells draw themselves. image *imagepreview.Thumbnail } // transcriptPreviewCmd returns a tea.Cmd that renders thumbnail previews for // the given clipboard images off the Bubble Tea event loop (decode + resample // must not block Update). The rendered previews are delivered via // imagePreviewReadyMsg, tagged with anchorID so the consumer can place them // directly after the originating user message. Returns nil when there is // nothing to render or no room for a preview; an empty result (terminal lacks // color support) yields a nil message that Bubble Tea ignores. // // A transcript preview uses whichever graphics mode the terminal supports, so // a submitted image looks the same as it did in the composer. Where // placeholder cells survive, the image travels as text and scrolls and clips // with its message for free. Where they do not — zellij strips the combining // marks they are built from — the image is painted over the screen instead, // and the model re-places it against the transcript on every frame, clipping // it to the rows the viewport still shows. See computeGfxPlacement. func (m *AppModel) transcriptPreviewCmd(images []uicore.ImageAttachment, anchorID string) tea.Cmd { if len(images) == 0 { return nil } cols := thumbMaxCols if m.width > 6 && m.width-6 < cols { cols = m.width - 6 } if cols < 1 { return nil } bg := style.GetTheme().Background imgs := images mode := termgfx.PreviewMode() caps := termgfx.Current() return func() tea.Msg { pad := lipgloss.NewStyle().PaddingLeft(style.ContentOffset) var previews []transcriptPreview var transmit strings.Builder for _, img := range imgs { var ( kt imagepreview.Thumbnail err error ) switch mode { case termgfx.ModePlaceholder: kt, err = imagepreview.RenderKitty(img.Data, cols, thumbMaxRows, caps.CellWidth, caps.CellHeight) case termgfx.ModeDirect: kt, err = imagepreview.RenderKittyDirect(img.Data, cols, thumbMaxRows, caps.CellWidth, caps.CellHeight) } if err == nil && kt.Cells != "" { transmit.WriteString(kt.Transmit) preview := transcriptPreview{cells: pad.Render(kt.Cells)} if kt.NeedsPlacement { thumb := kt preview.image = &thumb } previews = append(previews, preview) continue } if err != nil { log.Debug("kitty transcript preview failed, using half blocks", "error", err) } thumb, err := imagepreview.Render(img.Data, img.MediaType, cols, thumbMaxRows, bg) if err != nil || thumb == "" { continue } previews = append(previews, transcriptPreview{cells: pad.Render(thumb)}) } if len(previews) == 0 { return nil } return imagePreviewReadyMsg{ previews: previews, anchorID: anchorID, transmit: transmit.String(), } } } // lastMessageID returns the ID of the most recently added ScrollList message, // or "" when there are none. Used to anchor an async transcript preview to the // user message that was just printed. func (m *AppModel) lastMessageID() string { if len(m.messages) == 0 { return "" } return m.messages[len(m.messages)-1].ID() } // insertMessageAfter inserts item immediately after the message whose ID // matches anchorID. If anchorID is empty or not found, item is appended. func (m *AppModel) insertMessageAfter(anchorID string, item MessageItem) { idx := -1 if anchorID != "" { for i, msgItem := range m.messages { if msgItem.ID() == anchorID { idx = i break } } } if idx < 0 { m.messages = append(m.messages, item) return } m.messages = append(m.messages, nil) copy(m.messages[idx+2:], m.messages[idx+1:]) m.messages[idx+1] = item } // printUserMessage renders a user message into the ScrollList. func (m *AppModel) printUserMessage(text string) { // Check if this exact message was just added (prevents duplicates) if len(m.messages) > 0 { if lastMsg, ok := m.messages[len(m.messages)-1].(*TextMessageItem); ok { if lastMsg.role == "user" && lastMsg.content == text { return // Skip duplicate } } } now := time.Now() // Add to in-memory scrollList. The renderer call is deferred into a // closure so the block repaints itself after a theme change. msg := NewThemedMessageItem(generateMessageID(), "user", text, func() string { return m.renderer.RenderUserMessage(text, now).Content }) m.messages = append(m.messages, msg) // Refresh ScrollList content and scroll to bottom m.refreshContent() } // printAssistantMessage renders an assistant message into the ScrollList. func (m *AppModel) printAssistantMessage(text string) { if strings.TrimSpace(text) != "" { now := time.Now() modelName := m.paneModelName() // Add to in-memory scrollList. The renderer call is deferred into a // closure so the block repaints itself after a theme change. msg := NewThemedMessageItem(generateMessageID(), "assistant", text, func() string { return m.renderer.RenderAssistantMessage(text, now, modelName).Content }) m.messages = append(m.messages, msg) // Refresh ScrollList content and scroll to bottom m.refreshContent() } } // printToolResult renders a tool result message into the ScrollList. func (m *AppModel) printToolResult(evt app.ToolResultEvent) { m.turnToolCount++ // Keep the untruncated result as the item's raw content. The styled // rendering caps output (10 lines for generic results, 20 for diffs and // code) and elides long arguments in the header, so without this the // message inspector could only ever show the same elided text the // scrollback already displays. raw := toolRawContent(evt.ToolName, evt.ToolArgs, evt.Result, evt.IsError) // Add to in-memory scrollList. The renderer call is deferred into a // closure so the block repaints itself after a theme change. msg := NewThemedMessageItem(generateMessageID(), "tool", raw, func() string { return m.renderer.RenderToolMessage(evt.ToolName, evt.ToolArgs, evt.Result, evt.IsError).Content }).WithToolCall(ToolCallInfo{ // Kept structured as well as flattened: the inspector re-renders the // body uncapped, which needs the parts, not the transcript's summary. Name: evt.ToolName, Args: evt.ToolArgs, Result: evt.Result, IsError: evt.IsError, }) m.messages = append(m.messages, msg) // Refresh ScrollList content m.refreshContent() } // toolRawContent composes the full, untruncated record of a tool call for // the message inspector: the tool name, its arguments, and the complete // result body. // // The scrollback header shows only a truncated one-line summary of the // arguments (formatToolParams), so the full argument set — e.g. a long bash // command — is only recoverable from here. func toolRawContent(toolName, toolArgs, result string, isError bool) string { var b strings.Builder b.WriteString(toolName) if isError { b.WriteString(" (error)") } b.WriteString("\n") if args := strings.TrimSpace(toolArgs); args != "" && args != "{}" { b.WriteString("\n") b.WriteString(formatToolArgsForInspector(args)) b.WriteString("\n") } b.WriteString("\n") b.WriteString(result) return strings.TrimRight(b.String(), "\n") } // formatToolArgsForInspector renders tool arguments for full display. // // Single string values (a bash command, a file path) are printed as bare // "key: value" lines so the value stays copy-pasteable: JSON encoding would // escape every quote and collapse newlines into \n, which is exactly what // makes a long shell command unreadable. Structured values fall back to // indented JSON. func formatToolArgsForInspector(args string) string { var params map[string]any if err := json.Unmarshal([]byte(args), ¶ms); err != nil { // Not an object — show the argument text as-is. return args } if len(params) == 0 { return "" } keys := make([]string, 0, len(params)) for k := range params { keys = append(keys, k) } sort.Strings(keys) var b strings.Builder for _, k := range keys { if b.Len() > 0 { b.WriteString("\n") } b.WriteString(k) switch v := params[k].(type) { case string: if strings.Contains(v, "\n") { // Multi-line values start on their own line so the key // doesn't visually bind to only the first line. b.WriteString(":\n") } else { b.WriteString(": ") } b.WriteString(v) default: b.WriteString(": ") if enc, err := json.MarshalIndent(v, "", " "); err == nil { b.Write(enc) } else { fmt.Fprintf(&b, "%v", v) } } } return b.String() } // printErrorResponse renders an error message into the ScrollList. func (m *AppModel) printErrorResponse(evt app.StepErrorEvent) { if evt.Err != nil { errText := evt.Err.Error() now := time.Now() // Add to in-memory scrollList. The renderer call is deferred into a // closure so the block repaints itself after a theme change. msg := NewThemedMessageItem(generateMessageID(), "error", errText, func() string { return m.renderer.RenderErrorMessage(errText, now).Content }) m.messages = append(m.messages, msg) // Refresh ScrollList content m.refreshContent() } } // -------------------------------------------------------------------------- // Slash command handlers // -------------------------------------------------------------------------- // handleSlashCommand executes a recognized slash command and returns a tea.Cmd. // args contains any text after the command name (may be empty). func (m *AppModel) handleSlashCommand(sc *commands.SlashCommand, args string) tea.Cmd { if sc.Name != "/kill" { m.killConfirm = false } switch sc.Name { case "/quit": m.quitting = true return tea.Quit case "/kill": if strings.TrimSpace(args) != "" { m.killConfirm = false return nil } if !m.killConfirm { m.killConfirm = true m.printSystemMessage("Kill this session? Saved history will remain. Enter /kill again to confirm, or /kill cancel to cancel.") return nil } m.killConfirm = false if strings.TrimSpace(args) != "" { return nil } if m.killSession == nil { m.quitting = true return tea.Quit } if err := m.killSession(); err != nil { m.printSystemMessage(fmt.Sprintf("Could not stop hosted session: %v", err)) return nil } m.quitting = true return tea.Quit case "/help": m.openHelpModal() case "/tools": m.openToolsSheet() case "/servers": m.openServersSheet() case "/usage": m.openUsageSheet() case "/reset-usage": m.printResetUsage() case "/model": return m.handleModelCommand(args) case "/connect": return m.handleConnectCommand(args) case "/theme": return m.handleThemeCommand(args) case "/refresh": return m.handleRefreshCommand() case "/thinking": return m.handleThinkingCommand(args) case "/mode": return m.handleModelModeCommand(args) case "/jobs": m.handleJobsCommand(strings.Fields(args)) case "/cancel-job": m.handleCancelJobCommand(strings.Fields(args)) case "/subagents": return m.openSubagentInspector() case "/kill-subagent": m.handleKillSubagentCommand() case "/compact": return m.handleCompactCommand(args) case "/reload-ext": return m.handleReloadExtCommand() case "/shortcuts": return m.handleShortcutsCommand() case "/clear": if m.appCtrl != nil { m.appCtrl.ClearMessages() } // Clear the ScrollList so the conversation starts fresh. m.messages = []MessageItem{} m.printSystemMessage("Conversation cleared. Starting fresh.") case "/clear-queue": if m.appCtrl != nil { m.appCtrl.ClearQueue() } m.queuedMessages = m.queuedMessages[:0] m.steeringMessages = m.steeringMessages[:0] m.layoutDirty = true case "/tree": return m.handleTreeCommand() case "/fork": return m.handleForkCommand() case "/new": return m.handleNewCommand(args) case "/name": return m.handleNameCommand(args) case "/resume": return m.handleResumeCommand() case "/export": return m.handleExportCommand(args) case "/copy": return m.handleCopyCommand() case "/retry": return m.handleRetryCommand() case "/undo": return m.handleUndoCommand() case "/edit": return m.handleEditCommand(args) case "/share": return m.handleShareCommand() case "/import": return m.handleImportCommand(args) case "/session": return m.handleSessionInfoCommand() default: m.printSystemMessage(fmt.Sprintf("Unknown command: %s", sc.Name)) } return nil } // discardStepStreamingItems removes the streaming text and reasoning items // that the current step added to the ScrollList. Other items (for example // system or steering messages) stay. func (m *AppModel) discardStepStreamingItems() { mark := m.stepMessageMark if mark < 0 || mark > len(m.messages) { return } kept := m.messages[:mark] for _, item := range m.messages[mark:] { if _, ok := item.(*StreamingMessageItem); ok { continue } kept = append(kept, item) } clear(m.messages[len(kept):]) m.messages = kept m.refreshContent() } // stepResumeNotice is the system message for a step resume. func stepResumeNotice(e app.StepResumeEvent) string { reason := "transient provider error" if e.Error != nil { reason = e.Error.Error() } return fmt.Sprintf("Provider stream failed: %s\nRestarting the step in %s (resume %d). Partial output of the step was discarded; completed steps are kept.", reason, e.Delay.Round(100*time.Millisecond), e.Resume) } // quietScrollback reports whether a message can be added to the end of the // scrollback without harm: the composer has focus, and no item at the end // still receives chunks. After such an item, a message would make the next // chunk start a new item and split the stream. Message navigation must not // add to the list it browses either. func (m *AppModel) quietScrollback() bool { if m.state != stateInput || len(m.pendingStreamChunks) > 0 { return false } if len(m.messages) == 0 { return true } switch last := m.messages[len(m.messages)-1].(type) { case *StreamingMessageItem: return !last.streaming case *StreamingBashOutputItem: return last.complete } return true } // printSystemMessage renders a system-level message into the ScrollList. func (m *AppModel) printSystemMessage(text string) { now := time.Now() // Add to in-memory scrollList. The renderer call is deferred into a // closure so the block repaints itself after a theme change. msg := NewThemedMessageItem(generateMessageID(), "system", text, func() string { return m.renderer.RenderSystemMessage(text, now).Content }) m.messages = append(m.messages, msg) // Refresh ScrollList content m.refreshContent() } // printExtensionBlock renders a custom styled block from an extension with // caller-chosen border color and optional subtitle into the ScrollList. func (m *AppModel) printExtensionBlock(evt app.ExtensionPrintEvent) { // Add to in-memory scrollList. The renderer call is deferred into a // closure so the block repaints itself after a theme change. Note that // evt.BorderColor is the extension's own choice and stays fixed; only the // theme-derived parts of the block follow the active palette. msg := NewThemedMessageItem(generateMessageID(), "extension", evt.Text, func() string { text := evt.Text if evt.Markdown { // The block lays text into the same column as a bordered widget. text = widgetMarkdown(text, m.width, false) } return m.renderer.RenderExtensionBlock(text, evt.BorderColor, evt.Subtitle).Content }) m.messages = append(m.messages, msg) // Refresh ScrollList content m.refreshContent() } // handleExtensionCommand checks if the submitted text matches an extension- // registered slash command and returns a tea.Cmd that runs it. Returns nil // if no extension command matches. // // Extension commands execute asynchronously (via tea.Cmd goroutine) so they // can safely call blocking operations like ctx.PromptSelect() without // deadlocking the TUI's Update loop. The result is delivered back as an // extensionCmdResultMsg. // // Extension commands support arguments: "/sub list files" is split into // command name "/sub" and args "list files". func (m *AppModel) handleExtensionCommand(text string) tea.Cmd { if len(m.extensionCommands) == 0 { return nil } // Only consider inputs that look like slash commands. if !strings.HasPrefix(text, "/") { return nil } // Split: "/sub list files" → name="/sub", args="list files" name, args, _ := strings.Cut(text, " ") ecmd := commands.FindExtensionCommand(name, m.extensionCommands) if ecmd == nil { return nil } // Run the command in a dedicated goroutine — NOT as a tea.Cmd. Extension // commands may block on interactive prompts (ctx.PromptSelect etc.) which // wait for the TUI to respond via a channel. A blocking tea.Cmd can stall // BubbleTea's internal Cmd scheduler, causing intermittent freezes. // The goroutine delivers its result via SendUIMessage (prog.Send) instead. cmdName := ecmd.Name cmdExec := ecmd.Execute cmdArgs := args ctrl := m.appCtrl go func() { output, err := cmdExec(cmdArgs) ctrl.SendUIMessage(extensionCmdResultMsg{name: cmdName, output: output, err: err}) }() // Return a non-nil Cmd so the caller knows the command was handled // and doesn't fall through to the regular prompt path. The Cmd itself // is a no-op. return noopCmd } // handleMCPPromptCommand checks if the submitted text matches an MCP prompt // command (/: [args]) and returns a tea.Cmd that expands it // asynchronously. Returns nil if no MCP prompt matches. // // Arguments are parsed as key=value pairs. Positional arguments are mapped // to prompt argument names by order. func (m *AppModel) handleMCPPromptCommand(text string) tea.Cmd { if len(m.mcpPrompts) == 0 || m.expandMCPPrompt == nil { return nil } if !strings.HasPrefix(text, "/") { return nil } // Split: "/: key=val ..." → command, args cmdPart, argStr, _ := strings.Cut(text, " ") cmdPart = strings.TrimPrefix(cmdPart, "/") // Must contain a colon to be an MCP prompt command. serverName, promptName, ok := strings.Cut(cmdPart, ":") if !ok || serverName == "" || promptName == "" { return nil } // Find matching MCP prompt. var matched *MCPPromptInfo for i := range m.mcpPrompts { if m.mcpPrompts[i].ServerName == serverName && m.mcpPrompts[i].Name == promptName { matched = &m.mcpPrompts[i] break } } if matched == nil { return nil } // Parse arguments: support key=value pairs, with positional fallback. args := parseMCPPromptArgs(argStr, matched.Arguments) // Validate required arguments. for _, a := range matched.Arguments { if a.Required { if _, exists := args[a.Name]; !exists { m.printSystemMessage(fmt.Sprintf( "/%s:%s requires argument '%s'", serverName, promptName, a.Name, )) // Re-populate input for the user to add missing args. if ic, ok := m.input.(*InputComponent); ok { ic.textarea.SetValue(text + " ") ic.textarea.CursorEnd() } return noopCmd } } } // Expand asynchronously. expand := m.expandMCPPrompt ctrl := m.appCtrl go func() { result, err := expand(serverName, promptName, args) if err != nil { ctrl.SendUIMessage(mcpPromptResultMsg{err: err}) return } // Concatenate user-role messages as the prompt text and collect // any binary attachments from embedded resources. var parts []string var allFileParts []kit.LLMFilePart for _, msg := range result.Messages { if msg.Role == "user" { if msg.Content != "" { parts = append(parts, msg.Content) } allFileParts = append(allFileParts, msg.FileParts...) } } ctrl.SendUIMessage(mcpPromptResultMsg{ text: strings.Join(parts, "\n\n"), fileParts: allFileParts, }) }() return noopCmd } // parseMCPPromptArgs parses "key=value" pairs from a space-separated arg // string. Tokens without "=" are assigned to prompt arguments positionally. func parseMCPPromptArgs(argStr string, argDefs []MCPPromptArgInfo) map[string]string { result := make(map[string]string) if strings.TrimSpace(argStr) == "" { return result } tokens := strings.Fields(argStr) positionalIdx := 0 for _, tok := range tokens { if k, v, ok := strings.Cut(tok, "="); ok && k != "" { result[k] = v } else if positionalIdx < len(argDefs) { result[argDefs[positionalIdx].Name] = tok positionalIdx++ } } return result } // expandPromptTemplate checks if the submitted text matches a prompt template // and returns the expanded content with arguments substituted. // // Return values: // - (expanded, true, "") — template matched and expanded successfully // - (text, false, "") — no template matched; caller should treat text as-is // - ("", false, reason) — template matched but validation failed; reason // contains a user-facing error message (already printed to ScrollList) func (m *AppModel) expandPromptTemplate(text string) (string, bool, string) { if len(m.promptTemplates) == 0 { return text, false, "" } // Only consider inputs that look like slash commands. if !strings.HasPrefix(text, "/") { return text, false, "" } // Split: "/templatename arg1 arg2" → name="/templatename", args="arg1 arg2" name, args, _ := strings.Cut(text, " ") name = strings.TrimPrefix(name, "/") // Find matching template for _, tpl := range m.promptTemplates { if tpl.Name == name { // Validate that enough positional arguments were provided. required := tpl.RequiredArgs() if required > 0 { provided := len(prompts.ParseCommandArgs(args)) if provided < required { reason := fmt.Sprintf( "/%s requires %d argument(s), got %d", name, required, provided, ) m.printSystemMessage(reason) return "", false, reason } } return tpl.Expand(args), true, "" } } return text, false, "" } // refreshPromptTemplates reloads prompt templates from the provider callback // and updates the autocomplete entries. Called on ContentReloadEvent. func (m *AppModel) refreshPromptTemplates() { if m.getPromptTemplates == nil { return } newTemplates := m.getPromptTemplates() m.promptTemplates = newTemplates if ic, ok := m.input.(*InputComponent); ok { // Remove old prompt commands and add fresh ones. var kept []commands.SlashCommand for _, sc := range ic.commands { if sc.Category != "Prompts" { kept = append(kept, sc) } } for _, tpl := range newTemplates { kept = append(kept, commands.SlashCommand{ Name: "/" + tpl.Name, Description: tpl.Description, Category: "Prompts", HasArgs: tpl.HasArgPlaceholders(), }) } ic.commands = kept } } // refreshSkillItems reloads skill items from the provider callback and // updates the autocomplete entries. Called on ContentReloadEvent. func (m *AppModel) refreshSkillItems() { if m.getSkillItems == nil { return } newItems := m.getSkillItems() m.skillItems = newItems if ic, ok := m.input.(*InputComponent); ok { // Remove old Skills commands and add fresh ones. var kept []commands.SlashCommand for _, sc := range ic.commands { if sc.Category != "Skills" { kept = append(kept, sc) } } ic.commands = appendSkillCommands(kept, newItems) } } // appendSkillCommands appends one "/" autocomplete entry per skill to // cmds and returns the result. Skills whose slash name collides with an // existing entry (built-in, extension, MCP prompt or prompt template) are // skipped, because dispatch would never reach them; the collision is logged // so the author can rename one side. func appendSkillCommands(cmds []commands.SlashCommand, items []SkillItem) []commands.SlashCommand { taken := make(map[string]string, len(cmds)) for _, sc := range cmds { taken[sc.Name] = sc.Category for _, a := range sc.Aliases { taken[a] = sc.Category } } for _, s := range items { name := "/" + s.Name if cat, dup := taken[name]; dup { log.Warn("skill shadowed by existing slash command", "skill", s.Name, "path", s.Path, "shadowed_by", cat) continue } taken[name] = "Skills" cmds = append(cmds, commands.SlashCommand{ Name: name, Description: formatSkillDescription(s), Category: "Skills", HasArgs: true, }) } return cmds } // refreshExtensionItems reloads extension items from the provider callback // so the [Extensions] startup section reflects the current set after a // hot-reload. Called from the extReloadResultMsg handler. func (m *AppModel) refreshExtensionItems() { if m.getExtensionItems == nil { return } m.extensionItems = m.getExtensionItems() } // formatSkillDescription returns the autocomplete description for a skill. // Project-local skills are tagged so the user can see where a skill came // from; user-level skills (the common case) are shown without a prefix. Name // collisions are already resolved at load time (project wins), so a bare // name is never ambiguous. func formatSkillDescription(s SkillItem) string { desc := s.Description if s.Source == "project" { if desc == "" { return "(project)" } return "(project) " + desc } return desc } // refreshMCPPrompts reloads MCP prompts from the provider callback and // updates the autocomplete entries. Called on MCPToolsReadyEvent. func (m *AppModel) refreshMCPPrompts() { if m.getMCPPrompts == nil { return } newPrompts := m.getMCPPrompts() m.mcpPrompts = newPrompts if ic, ok := m.input.(*InputComponent); ok { // Remove old MCP Prompts commands and add fresh ones. var kept []commands.SlashCommand for _, sc := range ic.commands { if sc.Category != "MCP Prompts" { kept = append(kept, sc) } } for _, p := range newPrompts { hasArgs := false for _, a := range p.Arguments { if a.Required { hasArgs = true break } } kept = append(kept, commands.SlashCommand{ Name: fmt.Sprintf("/%s:%s", p.ServerName, p.Name), Description: p.Description, Category: "MCP Prompts", HasArgs: hasArgs, }) } ic.commands = kept } } // refreshToolNames reloads tool names from the provider callback. // Called on MCPToolsReadyEvent when background MCP tool loading completes. func (m *AppModel) refreshToolNames() { if m.getToolNames == nil { return } m.toolNames = m.getToolNames() } // refreshMCPToolCount reloads the MCP tool count from the provider callback. // Called on MCPToolsReadyEvent when background MCP tool loading completes. func (m *AppModel) refreshMCPToolCount() { if m.getMCPToolCount == nil { return } m.mcpToolCount = m.getMCPToolCount() } // printResetUsage resets usage statistics and prints a confirmation. func (m *AppModel) printResetUsage() { if m.usageTracker == nil { m.printSystemMessage("Usage tracking is not available for this model.") return } m.usageTracker.Reset() m.printSystemMessage("Usage statistics have been reset.") } // handleCompactCommand starts an async compaction. It returns a tea.Cmd that // prints a "compacting..." message and transitions to the working state. If // the app controller rejects the request (busy, closed) it prints an error // instead. customInstructions is optional text appended to the summary // prompt (e.g. "Focus on the API design decisions"). // handleReloadExtCommand reloads all extensions from disk asynchronously. // It returns a tea.Cmd to avoid calling prog.Send() from inside Update() // which would deadlock if any extension handler calls ctx.Print() during // SessionShutdown or SessionStart events. func (m *AppModel) handleReloadExtCommand() tea.Cmd { if m.reloadExtensions == nil { m.printSystemMessage("No extensions loaded.") return nil } reload := m.reloadExtensions return func() tea.Msg { err := reload() return extReloadResultMsg{err: err} } } func (m *AppModel) handleCompactCommand(customInstructions string) tea.Cmd { if m.appCtrl == nil { m.printSystemMessage("Compaction is not available.") return nil } if err := m.appCtrl.CompactConversation(customInstructions); err != nil { m.printSystemMessage(fmt.Sprintf("Cannot compact: %v", err)) return nil } // Transition to working state so the spinner shows while compaction runs. m.setAgentState(stateWorking) m.printSystemMessage("Compacting conversation...") var spinnerCmd tea.Cmd if m.stream != nil { _, spinnerCmd = m.stream.Update(app.SpinnerEvent{Show: true}) } return spinnerCmd } // printCompactResult renders the compaction summary in a styled block with // a distinct border color and a stats subtitle into the ScrollList. // flushStreamContent moves rendered content from the stream component into the // ScrollList and resets the stream. Called before tool calls (streaming // completes before tools fire). func (m *AppModel) flushStreamContent() { if m.stream == nil { return } content := m.stream.GetRenderedContent() if content == "" { return } m.stream.Reset() // Mark the existing StreamingMessageItem as complete. // The StreamingMessageItem already has the content from appendStreamingChunk(). if len(m.messages) > 0 { if streamMsg, ok := m.messages[len(m.messages)-1].(*StreamingMessageItem); ok { streamMsg.MarkComplete() m.refreshContent() } } } // finalizeStreamTurn closes out a turn's streaming output. Called from every // terminal step event (complete, cancelled, error). // // Stream chunks are mirrored into two places while a turn runs: the // StreamComponent's accumulator and a StreamingMessageItem in the ScrollList. // The ScrollList copy is marked complete so its live timer freezes, and the // StreamComponent is reset so its now-redundant copy is dropped. // // The reset matters most for interrupted turns. Without it the stale content // survives until the next SpinnerEvent{Show: true}, where // flushStreamAndPendingUserMessages() re-renders it as a fresh // StyledMessageItem — its alreadyInList check only inspects the trailing // message, which by then is the turn receipt or any system message printed // after the interrupt, so the whole response gets appended a second time. // // All buffered chunks are already applied to the ScrollList by the time a // terminal event is handled (see flushPendingStreamChunks in Update), so the // reset never loses content. func (m *AppModel) finalizeStreamTurn() { if len(m.messages) > 0 { if streamMsg, ok := m.messages[len(m.messages)-1].(*StreamingMessageItem); ok { streamMsg.MarkComplete() } } if m.stream != nil { m.stream.Reset() } m.refreshContent() m.layoutDirty = true } // flushPreviousStream moves the previous assistant response of the shown // pane from the stream component into the ScrollList. Called when a new step // starts, where all previous stream chunks have been processed. func (m *AppModel) flushPreviousStream() { if m.stream != nil { if content := m.stream.GetRenderedContent(); content != "" { m.stream.Reset() // Check whether the content is already in the ScrollList as a // StreamingMessageItem (created by appendStreamingChunk during // ReasoningChunkEvent / StreamChunkEvent). If so, just mark it // complete — creating a second StyledMessageItem would duplicate // the rendered block and shift mouse hit-testing coordinates. alreadyInList := false if len(m.messages) > 0 { if streamMsg, ok := m.messages[len(m.messages)-1].(*StreamingMessageItem); ok { streamMsg.MarkComplete() alreadyInList = true } } if !alreadyInList { now := time.Now() modelName := m.paneModelName() // Add to in-memory scrollList. The renderer call is deferred // into a closure so the block repaints on a theme change. msg := NewThemedMessageItem(generateMessageID(), "assistant", content, func() string { return m.renderer.RenderAssistantMessage(content, now, modelName).Content }) m.messages = append(m.messages, msg) } } } m.refreshContent() } // flushStreamAndPendingUserMessages moves the previous assistant response and // any pending queued user messages into the ScrollList. Called from // SpinnerEvent{Show: true} where all previous stream chunks are guaranteed to // have been processed. func (m *AppModel) flushStreamAndPendingUserMessages() { // 1. Flush previous stream content (assistant response). m.flushPreviousStream() // 2. Render pending user messages from the queue. for _, text := range m.pendingUserPrints { now := time.Now() // Add to in-memory scrollList. The renderer call is deferred into a // closure so the block repaints itself after a theme change. msg := NewThemedMessageItem(generateMessageID(), "user", text, func() string { return m.renderer.RenderUserMessage(text, now).Content }) m.messages = append(m.messages, msg) } m.pendingUserPrints = nil // Refresh ScrollList content once after all messages are added m.refreshContent() } // pendingStreamChunk is a buffered streaming chunk awaiting a coalesced // flush into the ScrollList. Consecutive chunks with the same role are // concatenated into a single entry. type pendingStreamChunk struct { role string content string } // chromeCache holds the rendered layout chrome measured by distributeHeight() // for reuse by View() within the same frame. type chromeCache struct { valid bool header string footer string above string below string queued string activity string subagents string input string } // isComposerTextKey reports whether msg is plain text editing in the // composer: a printable key or backspace, with no ctrl/alt/meta/super // modifier, while the composer has focus and no leader chord is armed. // Such keys never read the scrollback, so they need not flush buffered // stream chunks first. Every other key (scrolling, message navigation, // esc, enter, shortcuts, chords) still flushes. func (m *AppModel) isComposerTextKey(msg tea.KeyPressMsg) bool { if m.state != stateInput && m.state != stateWorking { return false } if m.leaderKeyActive || m.killSubagentOpen() { return false } if msg.Mod&(tea.ModCtrl|tea.ModAlt|tea.ModMeta|tea.ModSuper|tea.ModHyper) != 0 { return false } return msg.Text != "" || msg.Code == tea.KeyBackspace } // streamAppendFlushMsg fires when buffered stream chunks should be applied // to the ScrollList. See conversationPane.pendingStreamChunks. type streamAppendFlushMsg struct { // paneID names the pane whose chunks are buffered: "" for the parent // agent, a run ID for a subagent pane. paneID string } // streamAppendFlushTickCmd schedules a coalescing flush of buffered stream // chunks after delay. func streamAppendFlushTickCmd(paneID string, delay time.Duration) tea.Cmd { return tea.Tick(delay, func(_ time.Time) tea.Msg { return streamAppendFlushMsg{paneID: paneID} }) } const ( // streamFlushCostFactor sets how much idle time the event loop gets per // unit of streaming render time. At 2 the stream render occupies at most // about a third of the loop (cost / (2·cost + cost)), leaving the rest // for key presses and animation frames. streamFlushCostFactor = 2 // maxStreamFlushInterval caps the coalescing window so a very long // response still visibly advances several times per second. maxStreamFlushInterval = 250 * time.Millisecond ) // adaptiveStreamFlushInterval returns the coalescing window to use after a // streaming render that took cost. // // Every flush re-renders the whole streaming message (markdown, syntax // highlighting, wrapping), which is linear in its length: ~2ms at 2KB but // ~50ms at 60KB. With a fixed 16ms window a long response keeps the event // loop permanently busy and typing lags behind. Scaling the window with the // measured cost keeps short replies at ~60fps while bounding the share of // the loop that long ones consume. func adaptiveStreamFlushInterval(cost time.Duration) time.Duration { return min(max(streamFlushInterval, streamFlushCostFactor*cost), maxStreamFlushInterval) } // streamFlushDelay picks the coalescing window for the next flush from the // render cost of the message currently streaming. func (m *AppModel) streamFlushDelay() time.Duration { if n := len(m.messages); n > 0 { if s, ok := m.messages[n-1].(*StreamingMessageItem); ok { return adaptiveStreamFlushInterval(s.RenderCost()) } } return streamFlushInterval } // bufferStreamChunk adds a chunk to the pending buffer, concatenating // consecutive same-role chunks, and returns a flush tick command if one // isn't already scheduled. func (m *AppModel) bufferStreamChunk(role, content string) tea.Cmd { if n := len(m.pendingStreamChunks); n > 0 && m.pendingStreamChunks[n-1].role == role { m.pendingStreamChunks[n-1].content += content } else { m.pendingStreamChunks = append(m.pendingStreamChunks, pendingStreamChunk{role: role, content: content}) } if m.streamFlushPending { return nil } m.streamFlushPending = true return streamAppendFlushTickCmd(m.paneID, m.streamFlushDelay()) } // flushPendingStreamChunks applies all buffered stream chunks to the // ScrollList in arrival order. Called from the coalescing flush tick and // before handling any event whose behavior depends on the scrollback // contents (tool calls, reasoning completion, response completion, etc.). func (m *AppModel) flushPendingStreamChunks() { if len(m.pendingStreamChunks) == 0 { return } chunks := m.pendingStreamChunks m.pendingStreamChunks = m.pendingStreamChunks[:0] for i := range chunks { m.appendStreamingChunk(chunks[i].role, chunks[i].content) chunks[i] = pendingStreamChunk{} // release string for GC } } // appendStreamingChunk updates or creates a StreamingMessageItem in the ScrollList. // This enables live streaming text display within the ScrollList viewport (iteratr-style). func (m *AppModel) appendStreamingChunk(role, content string) { // Find the last message var lastMsg MessageItem if len(m.messages) > 0 { lastMsg = m.messages[len(m.messages)-1] } // If last message is a StreamingMessageItem with matching role, append to it if streamMsg, ok := lastMsg.(*StreamingMessageItem); ok && streamMsg.role == role { streamMsg.AppendChunk(content) // Invalidate cached height so GotoBottom sees the new size. if m.scrollList != nil { m.scrollList.InvalidateItemHeight(streamMsg.ID()) } // Auto-scroll to bottom if enabled (iteratr pattern) // Don't call SetItems() - the slice reference hasn't changed // // CRITICAL: never scroll the viewport while the user is actively // selecting text (mouse button held). Doing so shifts the // highlighted content out from under the cursor and produces the // off-by-N-row drift users see when copy-selecting during streaming. if m.scrollList != nil && !m.scrollList.IsMouseDown() { if m.scrollList.autoScroll { m.scrollList.GotoBottom() } else if m.scrollList.AtBottom() { // User manually scrolled back to bottom during streaming, // re-enable auto-scroll so they follow new content m.scrollList.autoScroll = true m.scrollList.GotoBottom() } } return } // Transition detected: mark previous reasoning message as complete when assistant text starts if streamMsg, ok := lastMsg.(*StreamingMessageItem); ok && streamMsg.role == "reasoning" && role == "assistant" { streamMsg.MarkComplete() } // Otherwise, create a new StreamingMessageItem id := generateMessageID() newMsg := NewStreamingMessageItem(id, role, m.paneModelName()) newMsg.AppendChunk(content) m.messages = append(m.messages, newMsg) // Refresh ScrollList and scroll to bottom m.refreshContent() } // currentScrollbackBounds returns the live (yOffset, viewportHeight) for the // scrollback region, computed from the current state — not from the cached // values populated inside View(). // // scrollbackYOffset and scrollList.height are refreshed once per render, so // any state change that resizes the header (extension widget toggles, // warning rows, queued messages, etc.) leaves the cached values one frame // stale. Mouse click handlers in Update() can then place the cursor on the // wrong line, producing the off-by-N-row drift seen during copy-selection. // // This recomputes the viewport height the same way distributeHeight() does // (running a fresh layout pass when dirty) and reuses the header height // measured by that pass — re-rendering the extension header on every mouse // motion event is needlessly expensive. func (m *AppModel) currentScrollbackBounds() (yOffset, viewportHeight int) { // Force a fresh layout if anything in Update() marked the state dirty; // otherwise scrollList.height still reflects the previous frame. if m.layoutDirty { m.distributeHeight() m.layoutDirty = false } yOffset = m.lastHeaderHeight if m.scrollList != nil { viewportHeight = m.scrollList.height } return yOffset, viewportHeight } // distributeHeight recalculates child component heights after a window resize, // queue change, widget update, or state transition, and propagates the computed // stream height to the StreamComponent. // // Layout (line counts): // // header = measured dynamically (0 if not set) // stream region = total - header - separator - widgets - queued - activity - input - widgets - statusBar - footer // separator = measured dynamically (0 when it renders nothing) // above widgets = measured dynamically // queued msgs = measured dynamically via lipgloss.Height() // activity row = 1 line while working, 0 when idle // input region = measured dynamically via lipgloss.Height() // below widgets = measured dynamically // status bar = 1 line (always present) // footer = measured dynamically (0 if not set) func (m *AppModel) distributeHeight() { vis := m.uiVis() // The separator is measured rather than assumed: it collapses to nothing // unless there are queued or steering messages to announce. separatorLines := 0 if !vis.HideSeparator { if sep := m.renderSeparator(); sep != "" { separatorLines = lipgloss.Height(sep) } } statusBarLines := 1 if vis.HideStatusBar { statusBarLines = 0 } // Every render below is stashed in m.chrome so View() can reuse the // strings instead of rendering the whole chrome a second time in the // same frame. The cache is invalidated at the start of every View(). m.chrome = chromeCache{valid: true} // Measure actual queued message height instead of using a fixed estimate, // since text wrapping at different widths changes the rendered line count. var queuedLines int if queuedView := m.renderQueuedMessages(); queuedView != "" { queuedLines = lipgloss.Height(queuedView) m.chrome.queued = queuedView } // Measure the activity row so the scrollback shrinks by exactly one line // when the agent starts working and grows back when it stops. var activityLines int if activityView := m.renderActivityRow(); activityView != "" { activityLines = lipgloss.Height(activityView) m.chrome.activity = activityView } var subagentLines int subagentView := m.renderBackgroundStatus() if subagentView != "" { subagentLines = lipgloss.Height(subagentView) m.chrome.subagents = subagentView } // Remember whether the row was present so syncActivityRow can detect the // next time the agent starts or stops working. m.lastActivityPresent = activityLines > 0 // Measure the actual rendered input (or prompt overlay) height so we // don't rely on a fragile constant that drifts when styling changes. // Use renderInput() which includes the editor interceptor's Render // wrapper so the measured height matches what View() actually renders. inputLines := 3 // fallback: composer bar padding(1) + one text row + padding(1) if m.state == statePrompt && m.prompt != nil { if rendered := m.prompt.Render(); rendered != "" { inputLines = lipgloss.Height(rendered) m.chrome.input = rendered } } else { if rendered := m.renderInput(); rendered != "" { inputLines = lipgloss.Height(rendered) m.chrome.input = rendered } } // Remember what the composer measured so syncInputHeight can detect the // next time it grows or shrinks. m.lastInputHeight = inputLines // Snapshot both slots so measurement and final rendering agree even if an // extension updates its widgets concurrently. Fill widgets cost no rows yet. var aboveWidgets, belowWidgets []WidgetData if m.getWidgets != nil { aboveWidgets = m.getWidgets("above") belowWidgets = m.getWidgets("below") } var fillKeys []string for _, slot := range []struct { name string widgets []WidgetData }{{"above", aboveWidgets}, {"below", belowWidgets}} { for _, w := range slot.widgets { if w.FillHeight && widgetContentWidth(m.width, w.NoBorder) > 0 { fillKeys = append(fillKeys, slot.name+":"+w.ID) } } } var widgetLines int if above := m.renderWidgets("above", aboveWidgets, nil); above != "" { widgetLines += lipgloss.Height(above) m.chrome.above = above } if below := m.renderWidgets("below", belowWidgets, nil); below != "" { widgetLines += lipgloss.Height(below) m.chrome.below = below } // Measure header/footer heights. var headerFooterLines int m.lastHeaderHeight = 0 if headerView := m.renderHeaderFooter("header", m.getHeader); headerView != "" { m.lastHeaderHeight = lipgloss.Height(headerView) headerFooterLines += m.lastHeaderHeight m.chrome.header = headerView } if footerView := m.renderHeaderFooter("footer", m.getFooter); footerView != "" { headerFooterLines += lipgloss.Height(footerView) m.chrome.footer = footerView } // Account for the transient confirmation row that View() injects between // the scrollback and the composer. Without subtracting it here the joined // view exceeds m.height and the bottom of the screen gets silently // clipped — which in turn invalidates scrollbackYOffset. While working // the confirmation lives in the activity row, which is measured // separately, so it costs nothing extra here. var warningLines int if m.ctrlCPressedOnce && !m.agentWorking() { warningLines++ } streamHeight := max(m.height-separatorLines-widgetLines-headerFooterLines-queuedLines-subagentLines-activityLines-inputLines-statusBarLines-warningLines, 0) m.fillActive = len(fillKeys) > 0 if m.fillActive { heights := make(map[string]int, len(fillKeys)) for i, key := range fillKeys { heights[key] = streamHeight / len(fillKeys) if i < streamHeight%len(fillKeys) { heights[key]++ } } m.chrome.above = m.renderWidgets("above", aboveWidgets, heights) m.chrome.below = m.renderWidgets("below", belowWidgets, heights) streamHeight = 0 } // Restore the selected message or bottom anchoring when the transcript // becomes visible again. Do not move a hidden transcript's selection. oldHeight := m.scrollList.height m.scrollList.SetHeight(streamHeight) m.scrollList.SetWidth(m.width) if oldHeight == 0 && streamHeight > 0 { if m.state == stateMessageNav { m.scrollList.EnsureVisible(m.scrollList.SelectedIndex()) } else if m.scrollList.autoScroll && !m.scrollList.sel.MouseDown { m.scrollList.GotoBottom() } } } // clamp constrains v to the range [lo, hi]. func clamp(v, lo, hi int) int { if v < lo { return lo } if v > hi { return hi } return v } // repeatRune returns a string consisting of n repetitions of r. func repeatRune(r rune, n int) string { if n <= 0 { return "" } runes := make([]rune, n) for i := range runes { runes[i] = r } return string(runes) } // -------------------------------------------------------------------------- // Extension shortcut matching // -------------------------------------------------------------------------- // lookupShortcut resolves a key press against the extension shortcut map. // // The terminal layer renders a key press two different ways and extension // authors legitimately use either. String() yields the key's *text* where one // exists, so Shift+A arrives as "A" and Shift+/ as "?". Keystroke() always // yields the modifier form, "shift+a" and "shift+/". Matching only String() // meant a perfectly reasonable binding like "shift+a" could never fire. // // Both forms are tried, text first, so a binding on the literal character // still wins over the modifier spelling of the same press. func lookupShortcut[T any](shortcuts map[string]T, msg tea.KeyPressMsg) (T, bool) { text := msg.String() if v, ok := shortcuts[text]; ok { return v, true } if stroke := msg.Keystroke(); stroke != text { if v, ok := shortcuts[stroke]; ok { return v, true } } var zero T return zero, false } // -------------------------------------------------------------------------- // Editor key remapping // -------------------------------------------------------------------------- // remapKey converts a key name string to a tea.KeyPressMsg for editor key // remapping. Returns the KeyPressMsg and true if the key name is recognized, // or a zero value and false if unknown. func remapKey(name string) (tea.KeyPressMsg, bool) { switch name { case "up": return tea.KeyPressMsg{Code: tea.KeyUp}, true case "down": return tea.KeyPressMsg{Code: tea.KeyDown}, true case "left": return tea.KeyPressMsg{Code: tea.KeyLeft}, true case "right": return tea.KeyPressMsg{Code: tea.KeyRight}, true case "backspace": return tea.KeyPressMsg{Code: tea.KeyBackspace}, true case "delete": return tea.KeyPressMsg{Code: tea.KeyDelete}, true case "enter": return tea.KeyPressMsg{Code: tea.KeyEnter}, true case "tab": return tea.KeyPressMsg{Code: tea.KeyTab}, true case "esc", "escape": return tea.KeyPressMsg{Code: tea.KeyEscape}, true case "home": return tea.KeyPressMsg{Code: tea.KeyHome}, true case "end": return tea.KeyPressMsg{Code: tea.KeyEnd}, true case "pgup", "pageup": return tea.KeyPressMsg{Code: tea.KeyPgUp}, true case "pgdown", "pagedown": return tea.KeyPressMsg{Code: tea.KeyPgDown}, true case "space": return tea.KeyPressMsg{Code: ' ', Text: " "}, true default: // Single printable character. runes := []rune(name) if len(runes) == 1 { return tea.KeyPressMsg{Code: runes[0], Text: name}, true } return tea.KeyPressMsg{}, false } } // -------------------------------------------------------------------------- // Model command handler // -------------------------------------------------------------------------- // openModelSelectorForProviderError opens the model selector when the active // provider is unusable and no selector is already open. It is used at startup // and after the session picker closes, so the user is never left on a dead // model without a way to switch. func (m *AppModel) openModelSelectorForProviderError() { if m.providerError == nil || m.modelSelector != nil { return } currentModel := m.providerName + "/" + m.modelName m.modelSelector = NewModelSelector(currentModel, m.width, m.height) m.state = stateModelSelector } // handleModelCommand handles the /model slash command. With no arguments, it // opens an interactive model selector overlay with fuzzy finding. With an // argument (e.g. "/model anthropic/claude-haiku-3-5-20241022"), it switches // to that model directly. func (m *AppModel) handleModelCommand(args string) tea.Cmd { if m.setModel == nil { m.printSystemMessage("Model switching is not available.") return nil } if args == "" { // Open the interactive model selector. currentModel := m.providerName + "/" + m.modelName m.modelSelector = NewModelSelector(currentModel, m.width, m.height) m.state = stateModelSelector return nil } // Direct model switch with the provided model string. m.switchModel(args) return nil } // switchModel performs a direct model switch, shared by the model selector // overlay and the /model slash command: it adjusts the thinking level when // the new model doesn't support the current one, calls the setModel // callback, updates display state, persists preferences, and emits the // ModelChange extension event. // // Display state is updated directly — we cannot use NotifyModelChanged // (prog.Send) from inside Update() without deadlocking BubbleTea. func (m *AppModel) switchModel(modelString string) { if m.setModel == nil { m.printSystemMessage("Model switching is not available.") return } previousModel := m.providerName + "/" + m.modelName // Staged thinking-level fallback, announced only once the model switch // below succeeds. Empty pendingFallbackTo means nothing to announce. var pendingFallbackFrom, pendingFallbackTo string // Check if thinking level needs adjustment for the new model. // Some models (e.g., OpenAI gpt-5.4) don't support "minimal" and require "none". if m.thinkingLevel != "" && m.thinkingLevel != "off" { if parts := strings.SplitN(modelString, "/", 2); len(parts) == 2 { providerName, modelName := parts[0], parts[1] currentLevel := models.ParseThinkingLevel(m.thinkingLevel) if !models.IsValidThinkingLevelForModel(currentLevel, providerName, modelName) { fallback := models.SuggestThinkingLevelFallback(currentLevel, providerName, modelName) if fallback != models.ThinkingOff { m.printSystemMessage(fmt.Sprintf( "Note: Model %s doesn't support '%s' thinking level. Adjusted to '%s'.", modelName, currentLevel, fallback, )) // Stage the announcement: the model switch below can // still fail, and a fallback tied to a model that was // never selected must not be reported as in effect. pendingFallbackFrom = m.thinkingLevel pendingFallbackTo = string(fallback) m.thinkingLevel = string(fallback) if m.setThinkingLevel != nil { if err := m.setThinkingLevel(string(fallback)); err != nil { pendingFallbackTo = "" } } go func() { _ = prefs.SaveThinkingLevelPreference(string(fallback)) }() } } } } if err := m.setModel(modelString); err != nil { m.printSystemMessage(fmt.Sprintf("Failed to switch model: %v", err)) return } // A working provider is installed now. Model changes always reset to default mode. m.providerError = nil m.modelMode = "" // Update display state directly (cannot use prog.Send from Update). if parts := strings.SplitN(modelString, "/", 2); len(parts) == 2 { m.providerName = parts[0] m.modelName = parts[1] } m.modelModes = modelModesFor(m.providerName, m.modelName) m.printSystemMessage(fmt.Sprintf("Switched to %s", modelString)) // Persist model selection for next launch. go func() { _ = prefs.SaveModelPreference(modelString) }() if m.emitModelChange != nil { emit := m.emitModelChange m.extEvents.dispatch(func() { emit(modelString, previousModel, "user") }) } // The switch succeeded, so a staged fallback is now genuinely in effect. if pendingFallbackTo != "" { m.notifyThinkingLevel(pendingFallbackTo, pendingFallbackFrom, "model_fallback") } } // notifyTurnState fires the OnTurnStateChange extension event. It is driven // from the single deferred busy/idle comparison in Update, so every path into // and out of the working state is reported — including shell commands and // cancellation, which never reach the agent loop. // // The handler runs in a goroutine: extension code must never execute inline in // Update, where a slow handler would stall BubbleTea's event loop. func (m *AppModel) notifyTurnState(state, previous string) { if m.emitTurnStateChange == nil { return } emit := m.emitTurnStateChange m.extEvents.dispatch(func() { emit(state, previous) }) } // notifyResize fires the OnTerminalResize extension event and refreshes the // terminal size on the extension context. Called from every site that handles // tea.WindowSizeMsg, including the prompt and overlay sub-loops that bypass // the main Update switch. func (m *AppModel) notifyResize() { if m.emitTerminalResize == nil { return } emit := m.emitTerminalResize w, h := m.width, m.height m.extEvents.dispatch(func() { emit(w, h) }) } // notifyThinkingLevel fires the OnThinkingLevelChange extension event. Skips // no-op changes so handlers are not woken for a level that did not move. func (m *AppModel) notifyThinkingLevel(newLevel, previousLevel, source string) { if m.emitThinkingLevelChange == nil || newLevel == previousLevel { return } emit := m.emitThinkingLevelChange m.extEvents.dispatch(func() { emit(newLevel, previousLevel, source) }) } // -------------------------------------------------------------------------- // Provider connect (/connect) command handler // -------------------------------------------------------------------------- // handleConnectCommand opens the provider picker. With an argument // ("/connect groq") the key input opens for that provider directly. func (m *AppModel) handleConnectCommand(args string) tea.Cmd { if m.saveProviderAPIKey == nil { m.printSystemMessage("Storing API keys is not available in this session.") return nil } m.providerConnect = NewProviderConnect(strings.TrimSpace(args), m.width, m.height) m.state = stateProviderConnect return m.providerConnect.Init() } // storeProviderKey persists the key through the wired callback. func (m *AppModel) storeProviderKey(providerID, key string) error { if m.saveProviderAPIKey == nil { return fmt.Errorf("storing API keys is not available in this session") } return m.saveProviderAPIKey(providerID, key) } // afterProviderKeySaved reports the save and, when the key belongs to the // active model's provider and that provider was unusable, rebuilds the // provider in place so the user can start chatting without a /model round // trip. func (m *AppModel) afterProviderKeySaved(providerID, providerName string) { path := tildeHome(credentialsPathOrDefault()) m.printSystemMessage(fmt.Sprintf("Saved %s API key to %s", providerName, path)) if m.providerError == nil { m.printSystemMessage(fmt.Sprintf("Use /model to pick a %s model.", providerName)) return } if !sameProviderID(providerID, m.providerName) { m.printSystemMessage(fmt.Sprintf( "The active model still uses %s, which has no key. Use /model to switch to a %s model, or /connect %s.", m.providerName, providerName, m.providerName)) return } if m.setModel == nil { return } current := m.providerName + "/" + m.modelName if err := m.setModel(current); err != nil { m.printSystemMessage(fmt.Sprintf("Key saved, but %s could not be started: %v", current, err)) return } m.providerError = nil m.printSystemMessage(fmt.Sprintf("Connected. %s is ready — type a message to start.", current)) } // sameProviderID compares provider IDs while treating the known aliases // (copilot/github-copilot, gemini/google) as equal. func sameProviderID(a, b string) bool { norm := func(s string) string { switch strings.ToLower(s) { case "github-copilot": return "copilot" case "gemini": return "google" default: return strings.ToLower(s) } } return norm(a) == norm(b) } // providerErrorNotice builds the user-facing text for a provider that could // not be created at startup: a missing credential, a failed OAuth token // refresh, or any other provider failure, plus the ways to fix it. func (m *AppModel) providerErrorNotice() string { if m.providerError == nil { return "" } model := m.providerName + "/" + m.modelName if mc := auth.AsMissingCredentials(m.providerError); mc != nil { name := mc.ProviderName if name == "" { name = mc.Provider } var b strings.Builder fmt.Fprintf(&b, "No API key is set for %s, so the model %s cannot be used yet.\n\n", name, model) if mc.Provider == "copilot" || mc.Provider == "github-copilot" { b.WriteString("GitHub Copilot uses device login: quit and run `kit auth login copilot`.") return b.String() } fmt.Fprintf(&b, " • Run /connect to add a key for %s (saved to %s)\n", name, tildeHome(credentialsPathOrDefault())) if len(mc.EnvVars) > 0 { fmt.Fprintf(&b, " • Or set %s in your environment and restart\n", strings.Join(mc.EnvVars, " or ")) } b.WriteString(" • Or run /model to pick a model from a provider that has a key") if mc.Hint != "" { b.WriteString("\n\n") b.WriteString(mc.Hint) } return b.String() } return fmt.Sprintf("The model %s is not available: %v\n\nRun /connect to add an API key or /model to switch models.", model, m.providerError) } // -------------------------------------------------------------------------- // Theme command handler // -------------------------------------------------------------------------- // handleThemeCommand switches the active color theme. With no arguments it // opens a modal picker (matching /model and /thinking). With a name argument // (e.g. "/theme catppuccin") it switches immediately. func (m *AppModel) handleThemeCommand(args string) tea.Cmd { if args == "" { m.themeSelector = NewThemeSelector(style.ActiveThemeName(), m.width, m.height) m.state = stateThemeSelector return nil } m.applyTheme(args) return nil } // applyTheme commits a theme change and prints a confirmation. Shared by the // /theme command path and the modal selector so both routes surface // the same message and repaint the same components. func (m *AppModel) applyTheme(name string) { if err := style.ApplyTheme(name); err != nil { m.printSystemMessage(fmt.Sprintf("Theme error: %v", err)) return } m.refreshTheme() m.printSystemMessage(fmt.Sprintf("Switched to theme: %s", name)) } // terminalRepaintCmd updates Bubble Tea's renderer before a complete repaint. func terminalRepaintCmd() tea.Cmd { profile := style.ColorProfile() return tea.Sequence(func() tea.Msg { return tea.ColorProfileMsg{Profile: profile} }, tea.ClearScreen) } // handleRefreshCommand never reads stdin directly: Bubble Tea owns terminal replies. func (m *AppModel) handleRefreshCommand() tea.Cmd { if m.readTerminalCapabilities != nil { if err := m.readTerminalCapabilities(); err != nil { m.printSystemMessage(fmt.Sprintf("Cannot read terminal capabilities: %v", err)) } else { m.printSystemMessage("Terminal colors refreshed. To query the client terminal again, use Ctrl-] r.") } } else { m.printSystemMessage("Terminal colors refreshed. Requested current terminal capabilities.") } // Also invalidate caches when the reported capabilities have not changed. style.SetTerminalCapabilities(style.IsDarkBackground(), style.ColorProfile()) m.refreshTheme() if m.readTerminalCapabilities != nil { return terminalRepaintCmd() } return tea.Batch(terminalRepaintCmd(), tea.RequestBackgroundColor, tea.RequestCapability("RGB"), tea.RequestCapability("Tc")) } // refreshTheme repaints everything that holds theme-derived styling after the // active theme has been replaced. // // Most of the UI reads the theme at render time and needs nothing. This covers // the exceptions: components that build styles once and keep them, and caches // keyed on something other than the theme. func (m *AppModel) refreshTheme() { for _, p := range m.allPanes() { p.renderer.UpdateTheme() if p.stream != nil { p.stream.UpdateTheme() } // Scrollback items repaint themselves lazily on the next draw (see // themeStamp), but their cached heights were measured against the // old rendering and a repainted block can occupy a different number // of lines. if p.scrollList != nil { p.scrollList.InvalidateHeights() } } // The composer paints its own background, so it has to be repainted too // or the bar keeps the previous theme's fill until restart. if ic, ok := m.input.(*InputComponent); ok { ic.UpdateTheme() } m.layoutDirty = true } // -------------------------------------------------------------------------- // Model mode command handler // -------------------------------------------------------------------------- func (m *AppModel) handleModelModeCommand(args string) tea.Cmd { name := strings.TrimSpace(args) if name == "" { m.modelModeSelector = NewModelModeSelector(m.modelModes, m.modelMode, m.width, m.height) m.state = stateModelModeSelector return nil } if name != "default" && name != "off" { found := false for _, option := range m.modelModes { if strings.EqualFold(option.Name, name) { name = option.Name found = true if !option.Supported { m.printSystemMessage(fmt.Sprintf("Mode %q is unavailable: %s", name, option.Reason)) return nil } break } } if !found { m.printSystemMessage(fmt.Sprintf("Unknown model mode %q", name)) return nil } } if name == "default" || name == "off" { name = "" } return m.applyModelMode(name) } func (m *AppModel) applyModelMode(mode string) tea.Cmd { if m.setModelMode == nil { return func() tea.Msg { return modelModeUpdateMsg{Mode: mode, Err: fmt.Errorf("model mode changes are not available")} } } setter := m.setModelMode return func() tea.Msg { return modelModeUpdateMsg{Mode: mode, Err: setter(mode)} } } // -------------------------------------------------------------------------- // Thinking command handler // -------------------------------------------------------------------------- // handleThinkingCommand changes or displays the current thinking/reasoning level. // With no arguments, it shows the current level. With a level argument (off, // minimal, low, medium, high) it switches to that level. func (m *AppModel) handleThinkingCommand(args string) tea.Cmd { if !m.isReasoningModel { m.printSystemMessage("Current model does not support thinking/reasoning.") return nil } if args == "" { // Match /model behaviour: open a modal picker directly, no space required. m.thinkingLevelSelector = NewThinkingLevelSelector( m.providerName, m.modelName, m.thinkingLevel, m.width, m.height) m.state = stateThinkingLevelSelector return nil } // Parse and validate the level. level := models.ParseThinkingLevel(args) // Levels the active model does not accept are substituted rather than // sent, since the provider would reject the request outright. if !models.IsValidThinkingLevelForModel(level, m.providerName, m.modelName) { fallback := models.SuggestThinkingLevelFallback(level, m.providerName, m.modelName) if fallback == models.ThinkingOff && level != models.ThinkingOff { m.printSystemMessage(fmt.Sprintf( "Model %s does not support the '%s' thinking level. Supported: %v", m.modelName, level, models.SupportedThinkingLevels(m.providerName, m.modelName))) return nil } m.printSystemMessage(fmt.Sprintf( "Note: Model %s doesn't support '%s' thinking level. Using '%s' instead.", m.modelName, level, fallback)) level = fallback } // Apply the change. m.applyThinkingLevel(level) return nil } // applyThinkingLevel commits a thinking-level change: it persists the value, // invokes the provider callback, emits the extension event, and prints a // confirmation. Shared by the /thinking command path and the modal // selector so both routes surface the same message and fire the same events. func (m *AppModel) applyThinkingLevel(level models.ThinkingLevel) { previousLevel := m.thinkingLevel m.thinkingLevel = string(level) if m.setThinkingLevel != nil { go func() { // Announce only after the provider accepts the new level, so // ThinkingLevelChangeEvent.NewLevel reflects reality. if err := m.setThinkingLevel(string(level)); err == nil { m.notifyThinkingLevel(string(level), previousLevel, "user") } }() } else { m.notifyThinkingLevel(string(level), previousLevel, "user") } // Persist thinking level for next launch. go func() { _ = prefs.SaveThinkingLevelPreference(string(level)) }() m.printSystemMessage(fmt.Sprintf("Thinking level set to: %s — %s", level, models.ThinkingLevelDescription(level))) } // -------------------------------------------------------------------------- // Tree session command handlers // -------------------------------------------------------------------------- // handleTreeCommand opens the tree selector overlay. func (m *AppModel) handleTreeCommand() tea.Cmd { snap, ok := m.appCtrl.SessionSnapshot() if !ok { m.printSystemMessage("No tree session active. Start with `--continue` or `--resume` to enable tree sessions.") return nil } if snap.EntryCount == 0 { m.printSystemMessage("No entries in session yet.") return nil } m.treeSelector = NewTreeSelector(m.appCtrl.SessionTree(), snap.LeafID, m.width, m.height) m.state = stateTreeSelector return nil } // handleForkCommand creates a branch from the current position. Like /tree // but opens the selector directly for fork semantics. // Unlike /tree which shows the full tree, /fork shows only user messages // (matching Pi's behavior) and creates a new session file when a message is selected. func (m *AppModel) handleForkCommand() tea.Cmd { snap, ok := m.appCtrl.SessionSnapshot() if !ok { m.printSystemMessage("No tree session active. Start with `--continue` or `--resume` to enable tree sessions.") return nil } if snap.EntryCount == 0 { m.printSystemMessage("No entries to fork from.") return nil } // Use the fork-specific selector that shows only user messages. m.treeSelector = NewTreeSelectorForFork(m.appCtrl.SessionTree(), snap.LeafID, m.width, m.height) m.state = stateTreeSelector return nil } // handleNewCommand starts a completely new session (Pi-style /new behavior). // Creates a new session file, discarding all context from the previous conversation. // If initialPrompt is non-empty it is submitted as the first user turn of the // new session, with @file references expanded the same way they are for // regular user input. func (m *AppModel) handleNewCommand(initialPrompt string) tea.Cmd { initialPrompt = strings.TrimSpace(initialPrompt) // Emit before-session-switch event in a goroutine so that extension // handlers can call blocking operations (e.g. ctx.PromptConfirm) without // deadlocking the BubbleTea event loop. if m.emitBeforeSessionSwitch != nil { emit := m.emitBeforeSessionSwitch ctrl := m.appCtrl go func() { cancelled, reason := emit("new", initialPrompt) ctrl.SendUIMessage(beforeSessionSwitchResultMsg{ cancelled: cancelled, reason: reason, initialPrompt: initialPrompt, }) }() return noopCmd } return m.performNewSession(initialPrompt) } // performNewSession performs the actual session reset. Called either directly // (when no before-hook exists) or after the async hook completes. // Matches Pi behavior: creates a completely new session file, discarding all // context from the previous conversation. If initialPrompt is non-empty it // is submitted as the first user turn (with @file expansion). func (m *AppModel) performNewSession(initialPrompt string) tea.Cmd { if _, ok := m.appCtrl.SessionSnapshot(); !ok { // No tree session — just clear messages. if m.appCtrl != nil { m.appCtrl.ClearMessages() } // Reset usage statistics for fresh session if m.usageTracker != nil { m.usageTracker.Reset() } // Clear the ScrollList so the new session starts fresh. m.messages = []MessageItem{} m.printSystemMessage("Conversation cleared. Starting fresh.") cmd := m.submitInitialPrompt(initialPrompt) m.signalNewSessionResult(nil) return cmd } // Create a brand new session file (Pi-style /new behavior) and switch to // it, closing the old one. if err := m.appCtrl.NewSession(m.cwd); err != nil { m.printSystemMessage(fmt.Sprintf("Failed to create new session: %v", err)) m.signalNewSessionResult(fmt.Errorf("create new session: %w", err)) return nil } // Reset usage statistics for the new session if m.usageTracker != nil { m.usageTracker.Reset() } // Clear the ScrollList so the new session starts fresh. m.messages = []MessageItem{} m.printSystemMessage("New session started. Previous conversation saved.") cmd := m.submitInitialPrompt(initialPrompt) m.signalNewSessionResult(nil) return cmd } // signalNewSessionResult delivers the outcome of an extension-triggered // NewSession request (if one is in flight) and clears the response channel. // Safe to call when no request is pending. func (m *AppModel) signalNewSessionResult(err error) { if m.newSessionResultCh == nil { return } ch := m.newSessionResultCh m.newSessionResultCh = nil // Channel is buffered (cap >= 1) by contract — send is non-blocking. ch <- err } // submitInitialPrompt is the shared submission path used by /new // and ctx.NewSession(prompt). It mirrors the SubmitMsg handler: @file // references are expanded via fileutil.ProcessFileAttachments and the // resulting prompt is forwarded to AppController.Run / RunWithFiles. // Returns nil when prompt is empty. func (m *AppModel) submitInitialPrompt(prompt string) tea.Cmd { prompt = strings.TrimSpace(prompt) if prompt == "" || m.appCtrl == nil { return nil } processedText := prompt var fileParts []kit.LLMFilePart if m.cwd != "" { result := fileutil.ProcessFileAttachments(prompt, m.cwd, m.mcpResourceReader) processedText = result.ProcessedText for _, fp := range result.FileParts { fileParts = append(fileParts, kit.LLMFilePart{ Filename: fp.Filename, Data: fp.Data, MediaType: fp.MediaType, }) } } displayText := prompt if len(fileParts) > 0 { displayText = fmt.Sprintf("%s\n[%d file(s) attached]", prompt, len(fileParts)) } var qLen int if len(fileParts) > 0 { qLen = m.appCtrl.RunWithFiles(processedText, fileParts) } else { qLen = m.appCtrl.Run(processedText) } if qLen > 0 { m.queuedMessages = append(m.queuedMessages, displayText) m.layoutDirty = true } else { m.pendingUserPrints = append(m.pendingUserPrints, displayText) m.flushStreamAndPendingUserMessages() } return nil } // performFork creates a new session by forking from the target entry. // This matches Pi's /fork behavior: it creates a completely new session file // with the history up to the target point, then switches to that session. // Called either directly (when no before-hook exists) or after the async // before-fork hook completes. func (m *AppModel) performFork(targetID string, isUser bool, userText string) tea.Cmd { if _, ok := m.appCtrl.SessionSnapshot(); !ok { m.printSystemMessage("No tree session active.") return nil } // Create a new session by forking from the target entry. This writes a // new session file with the history up to the target point and switches // to it. if err := m.appCtrl.ForkSession(m.cwd, targetID); err != nil { m.printSystemMessage(fmt.Sprintf("Failed to fork session: %v", err)) return nil } // Reset usage statistics for the new session. if m.usageTracker != nil { m.usageTracker.Reset() } // Clear the scroll list and populate all messages from the forked history. m.messages = []MessageItem{} m.renderSessionHistory() // If it was a user message, populate the input with the text. if isUser && userText != "" { if ic, ok := m.input.(*InputComponent); ok { ic.textarea.SetValue(userText) ic.textarea.CursorEnd() } } m.printSystemMessage("Forked to new session. Edit and resubmit to continue.") return nil } // handleNameCommand sets a display name for the current session. // Usage: /name — sets the session name. // // /name — shows the current name. func (m *AppModel) handleNameCommand(args string) tea.Cmd { snap, ok := m.appCtrl.SessionSnapshot() if !ok { m.printSystemMessage("No tree session active.") return nil } if args == "" { // No argument — show current name. if snap.Name != "" { m.printSystemMessage(fmt.Sprintf("Session name: %q\nTo rename: `/name `", snap.Name)) } else { m.printSystemMessage("Session has no name. Set one with: `/name `") } return nil } // Set the session name. if err := m.appCtrl.SetSessionName(args); err != nil { m.printSystemMessage(fmt.Sprintf("Failed to set session name: %v", err)) return nil } m.printSystemMessage(fmt.Sprintf("Session named %q", args)) return nil } // handleCopyCommand copies the last user or assistant message to the system // clipboard. Skips transient system messages (e.g. /help output) so the user // gets the actual last conversational message. func (m *AppModel) handleCopyCommand() tea.Cmd { if len(m.messages) == 0 { m.printSystemMessage("No messages to copy.") return nil } var ( text string role string ) for _, v := range slices.Backward(m.messages) { switch msg := v.(type) { case *TextMessageItem: if msg.role == "user" || msg.role == "assistant" { text = msg.content role = msg.role } case *StreamingMessageItem: if msg.role == "assistant" || msg.role == "reasoning" { text = msg.content.String() role = msg.role } } if text != "" { break } } if strings.TrimSpace(text) == "" { m.printSystemMessage("No copyable message found.") return nil } m.printSystemMessage(fmt.Sprintf( "Copied last %s message to clipboard (%d chars).", role, len([]rune(text)), )) return clipboard.CopyToClipboard(text) } // handleRetryCommand resubmits the most recent user message on the current // branch. Used to recover from transient provider errors (overloaded, // timeout) without users having to retype — and without the duplicate-user- // message bloat that retyping creates. // // Flow: // 1. App.PopLastUserMessage() truncates the tree at the parent of the last // user message and returns its text + any image parts. The failed turn's // entries become orphaned (still on disk, off-branch) so they will not // be re-sent to the LLM. // 2. The visible message list is rebuilt from the truncated branch so the // prior user message + any partial assistant + error rendering vanish. // 3. The prompt is resubmitted via Run/RunWithFiles, mirroring the normal // SubmitMsg display path (badge formatting, pending-prints flush, // stateWorking transition). func (m *AppModel) handleRetryCommand() tea.Cmd { if m.appCtrl == nil { m.printSystemMessage("App controller unavailable.") return nil } prompt, files, err := m.appCtrl.PopLastUserMessage() if err != nil { m.printSystemMessage(fmt.Sprintf("Cannot retry: %v", err)) return nil } // Rebuild the visible ScrollList from the truncated branch so the failed // turn's user message and any partial assistant/error rendering disappear // before the resubmit prints a fresh user message. m.messages = []MessageItem{} m.renderSessionHistory() // Mirror SubmitMsg's badge formatting for the display text. var imageCount, fileOnlyCount int for _, f := range files { if strings.HasPrefix(f.MediaType, "image/") { imageCount++ } else { fileOnlyCount++ } } displayText := prompt if imageCount > 0 || fileOnlyCount > 0 { var badges []string if imageCount > 0 { badges = append(badges, fmt.Sprintf("%d image(s) pasted", imageCount)) } if fileOnlyCount > 0 { badges = append(badges, fmt.Sprintf("%d file(s) attached", fileOnlyCount)) } displayText = fmt.Sprintf("%s\n[%s]", prompt, strings.Join(badges, ", ")) } var qLen int if len(files) > 0 { qLen = m.appCtrl.RunWithFiles(prompt, files) } else { qLen = m.appCtrl.Run(prompt) } if qLen > 0 { m.queuedMessages = append(m.queuedMessages, displayText) m.layoutDirty = true } else { m.pendingUserPrints = append(m.pendingUserPrints, displayText) m.flushStreamAndPendingUserMessages() } if !m.agentWorking() { m.setAgentState(stateWorking) } return nil } // handleUndoCommand removes the most recent user message on the current // branch along with any assistant/tool responses that followed it, then // restores the popped prompt text into the input textarea so the user can // edit and resubmit (or simply discard it). // // Unlike /retry, no resubmit is performed — this is a pure rollback of the // last turn. The orphaned entries remain in the session file under a // different leaf (so they are recoverable via /tree), but they are no // longer on the active branch and will not be re-sent to the LLM. func (m *AppModel) handleUndoCommand() tea.Cmd { if m.appCtrl == nil { m.printSystemMessage("App controller unavailable.") return nil } prompt, files, err := m.appCtrl.PopLastUserMessage() if err != nil { m.printSystemMessage(fmt.Sprintf("Cannot undo: %v", err)) return nil } // Rebuild the visible ScrollList from the truncated branch so the // popped user message and any assistant/tool rendering disappear. m.messages = []MessageItem{} m.renderSessionHistory() // Restore the popped prompt text into the input so the user can edit // and resubmit. Mirrors how /fork handles a user message. Image/file // attachments cannot be re-inserted into the textarea, so we surface a // note when any are dropped. if ic, ok := m.input.(*InputComponent); ok { ic.textarea.SetValue(prompt) ic.textarea.CursorEnd() } msg := "Removed the last user message and any responses." if len(files) > 0 { msg = fmt.Sprintf("%s (%d attached file(s) were dropped — re-attach if needed)", msg, len(files)) } m.printSystemMessage(msg) return nil } // handleEditCommand opens the supplied path in $EDITOR via tea.ExecProcess, // pausing the TUI for the duration of the editor session. The path is // resolved relative to cwd; ~/ and absolute paths are honoured. Non-existent // paths are allowed — most editors will create the file on save. // // On exit an editFileMsg is emitted with the resolved path (or error) so the // Update loop can report the result. The textarea is not touched — use // Ctrl+X e if you want to round-trip a prompt through $EDITOR instead. func (m *AppModel) handleEditCommand(args string) tea.Cmd { path := strings.TrimSpace(args) if path == "" { m.printSystemMessage("Usage: `/edit ` — or type `/edit ` and pick a file from the popup.") return nil } // Strip optional surrounding double-quotes (the autocomplete inserts // these when a path contains spaces). if len(path) >= 2 && strings.HasPrefix(path, `"`) && strings.HasSuffix(path, `"`) { path = path[1 : len(path)-1] } // Resolve ~/, relative, and absolute paths against cwd. resolved := path if strings.HasPrefix(resolved, "~/") { if home, err := os.UserHomeDir(); err == nil { resolved = filepath.Join(home, resolved[2:]) } } if !filepath.IsAbs(resolved) { cwd, err := os.Getwd() if err == nil { resolved = filepath.Join(cwd, resolved) } } resolved = filepath.Clean(resolved) // Reject paths that exist but are directories — $EDITOR semantics vary. if info, err := os.Stat(resolved); err == nil && info.IsDir() { m.printSystemMessage(fmt.Sprintf("`%s` is a directory, not a file.", resolved)) return nil } editorApp := os.Getenv("VISUAL") if editorApp == "" { editorApp = os.Getenv("EDITOR") } if editorApp == "" { m.printSystemMessage("Set `$EDITOR` or `$VISUAL` to use `/edit`") return nil } editorCmd, cmdErr := editor.Command(editorApp, resolved) if cmdErr != nil { m.printSystemMessage(fmt.Sprintf("Failed to open editor: %v", cmdErr)) return nil } return tea.ExecProcess(editorCmd, func(err error) tea.Msg { return editFileMsg{path: resolved, err: err} }) } // handleExportCommand exports the current session to a file. // Usage: /export — copies the JSONL file to cwd with a descriptive name. // // /export path.jsonl — copies to the specified path. func (m *AppModel) handleExportCommand(args string) tea.Cmd { dstPath, written, err := m.appCtrl.ExportSession(args) switch { case errors.Is(err, app.ErrNoSession): m.printSystemMessage("No tree session active.") case errors.Is(err, app.ErrSessionNotPersisted): m.printSystemMessage("Session is in-memory (not persisted). Nothing to export.") case err != nil: m.printSystemMessage(fmt.Sprintf("Failed to export session: %v", err)) default: m.printSystemMessage(fmt.Sprintf("Session exported to: %s (%d bytes)", dstPath, written)) } return nil } // handleShareCommand uploads the current session as a GitHub Gist and prints // a shareable viewer URL. Requires the GitHub CLI (gh) to be installed and // authenticated. func (m *AppModel) handleShareCommand() tea.Cmd { // Check the session is shareable before probing for gh, so an in-memory // session reports that rather than a missing-CLI error. snap, ok := m.appCtrl.SessionSnapshot() if !ok { m.printSystemMessage("No tree session active.") return nil } if snap.FilePath == "" { m.printSystemMessage("Session is in-memory (not persisted). Nothing to share.") return nil } // Check that gh CLI is available. if _, err := exec.LookPath("gh"); err != nil { m.printSystemMessage("GitHub CLI (gh) is not installed. Install it from https://cli.github.com/") return nil } // Check that gh is authenticated. authCheck := exec.Command("gh", "auth", "status") if err := authCheck.Run(); err != nil { m.printSystemMessage("GitHub CLI is not logged in. Run 'gh auth login' first.") return nil } // The app layer writes the session plus a system-prompt entry recording // the context the conversation ran under; we own the temp file from here. tmpPath, err := m.appCtrl.WriteShareableSession( viper.GetString("system-prompt"), viper.GetString("model"), ) if err != nil { m.printSystemMessage(fmt.Sprintf("Failed to share session: %v", err)) return nil } m.printSystemMessage("Uploading session to GitHub Gist...") // Run gh gist create in background to avoid blocking the UI. return func() tea.Msg { defer func() { _ = os.Remove(tmpPath) }() cmd := exec.Command("gh", "gist", "create", tmpPath, "--desc", "Kit session shared via /share") output, err := cmd.Output() if err != nil { return shareResultMsg{err: fmt.Errorf("failed to create gist: %w", err)} } // gh outputs the gist URL like: https://gist.github.com/username/abc123def456 gistURL := strings.TrimSpace(string(output)) // Extract gist ID (last path segment). parts := strings.Split(gistURL, "/") gistID := parts[len(parts)-1] viewerURL := fmt.Sprintf("https://go-kit.dev/session/#%s", gistID) return shareResultMsg{gistURL: gistURL, viewerURL: viewerURL} } } // handleImportCommand imports a session from a JSONL file. // Usage: /import path.jsonl func (m *AppModel) handleImportCommand(args string) tea.Cmd { if args == "" { m.printSystemMessage("Usage: `/import `") return nil } if m.switchSession == nil { m.printSystemMessage("Session switching is not available.") return nil } // Verify file exists before attempting to switch. if _, err := os.Stat(args); err != nil { m.printSystemMessage(fmt.Sprintf("File not found: %s", args)) return nil } if err := m.switchSession(args); err != nil { m.printSystemMessage(fmt.Sprintf("Failed to import session: %v", err)) return nil } m.renderSessionHistory() m.printSystemMessage(fmt.Sprintf("Session imported from: %s", args)) return nil } // handleResumeCommand opens the session picker so the user can switch sessions. func (m *AppModel) handleResumeCommand() tea.Cmd { if m.switchSession == nil { m.printSystemMessage("Session switching is not available.") return nil } m.sessionSelector = NewSessionSelector(m.appCtrl, m.cwd, m.width, m.height) m.state = stateSessionSelector return nil } // renderSessionHistory walks the current session branch and renders all // messages (user, assistant, tool calls/results) into the ScrollList. // This gives the user visual context of the conversation when resuming or // importing a session. Call this after switchSession succeeds. func (m *AppModel) renderSessionHistory() { if _, ok := m.appCtrl.SessionSnapshot(); !ok { // No session to render from — leave the transcript untouched rather // than blanking a conversation the session layer knows nothing about // (e.g. an in-memory run). return } history := m.appCtrl.SessionHistory() // Clear existing messages so we start fresh with the resumed session. // This must happen even when the history is empty: /retry and /undo pop // the last user message and can leave the branch with no messages at all, // and forking or resuming can land on an empty session. Returning early // here would leave the previous transcript on screen. m.messages = []MessageItem{} // First pass: build a map of tool call ID → {name, args} from assistant // messages so we can pair them with tool results. type toolCallInfo struct { Name string Args string } toolCallMap := make(map[string]toolCallInfo) for _, msg := range history { if msg.Role != message.RoleAssistant { continue } for _, tc := range msg.ToolCalls() { toolCallMap[tc.ID] = toolCallInfo{Name: tc.Name, Args: tc.Input} } } // Second pass: create MessageItems for each message in order. for _, msg := range history { switch msg.Role { case message.RoleUser: text := strings.TrimSpace(msg.Content()) if text != "" { createdAt := msg.CreatedAt item := NewThemedMessageItem(generateMessageID(), "user", text, func() string { return m.renderer.RenderUserMessage(text, createdAt).Content }) m.messages = append(m.messages, item) } case message.RoleAssistant: // First render any reasoning/thinking content reasoning := msg.Reasoning() if reasoning.Thinking != "" { thinking, createdAt := reasoning.Thinking, msg.CreatedAt item := NewThemedMessageItem(generateMessageID(), "reasoning", thinking, func() string { return m.renderer.RenderReasoningBlock(thinking, createdAt).Content }) m.messages = append(m.messages, item) } // Then render the text content text := strings.TrimSpace(msg.Content()) if text != "" { modelName := m.modelName if msg.Model != "" { modelName = msg.Model } createdAt := msg.CreatedAt item := NewThemedMessageItem(generateMessageID(), "assistant", text, func() string { return m.renderer.RenderAssistantMessage(text, createdAt, modelName).Content }) m.messages = append(m.messages, item) } // Tool calls from assistant messages are rendered when we // encounter their corresponding tool results below. case message.RoleTool: for _, tr := range msg.ToolResults() { toolName := tr.Name toolArgs := "" if info, ok := toolCallMap[tr.ToolCallID]; ok { if toolName == "" { toolName = info.Name } toolArgs = info.Args } // Retain the full call record so a resumed session's tool // messages stay inspectable, exactly as live ones are. raw := toolRawContent(toolName, toolArgs, tr.Content, tr.IsError) content, isError := tr.Content, tr.IsError item := NewThemedMessageItem(generateMessageID(), "tool", raw, func() string { return m.renderer.RenderToolMessage(toolName, toolArgs, content, isError).Content }).WithToolCall(ToolCallInfo{ Name: toolName, Args: toolArgs, Result: content, IsError: isError, }) m.messages = append(m.messages, item) } } } // Update the ScrollList with the rebuilt message list. // Defer GotoBottom until after the next distributeHeight() so the // scroll position is calculated with the correct viewport height. m.refreshContent() m.layoutDirty = true m.pendingGotoBottom = true } // -------------------------------------------------------------------------- // Cancel timer command // -------------------------------------------------------------------------- // cancelTimerCmd returns a tea.Cmd that fires CancelTimerExpiredMsg after 2s. // This is used for the double-tap ESC cancel flow. func cancelTimerCmd() tea.Cmd { return tea.Tick(2*time.Second, func(_ time.Time) tea.Msg { return uicore.CancelTimerExpiredMsg{} }) } // ctrlCResetCmd returns a tea.Cmd that fires CtrlCResetMsg after 3s. // This resets the ctrlCPressedOnce flag so the next Ctrl+C will clear input again. func ctrlCResetCmd() tea.Cmd { return tea.Tick(3*time.Second, func(_ time.Time) tea.Msg { return uicore.CtrlCResetMsg{} }) } // -------------------------------------------------------------------------- // Interactive prompt support // -------------------------------------------------------------------------- // externalEditorMsg is sent when the user returns from $EDITOR after // composing a prompt via the Ctrl+X e chord. type externalEditorMsg struct { text string err error } // editFileMsg is sent when the user returns from $EDITOR after invoking the // /edit slash command on a specific file. Unlike externalEditorMsg, no text // is read back — the user edited the file directly on disk. type editFileMsg struct { path string err error } // shareResultMsg carries the result of an async gist upload. type shareResultMsg struct { err error gistURL string viewerURL string } // extReloadResultMsg carries the result of an asynchronously executed // /reload-ext command. The reload runs async to avoid deadlocking the // TUI event loop (extension handlers may call prog.Send via ctx.Print). type extReloadResultMsg struct { err error } // extensionCmdResultMsg carries the result of an asynchronously executed // extension slash command. Extension commands run async (via tea.Cmd) so they // can safely call blocking operations like ctx.PromptSelect(). type extensionCmdResultMsg struct { name string output string err error } // mcpPromptResultMsg carries the result of an asynchronously expanded MCP // prompt. The expansion runs in a goroutine since it contacts the MCP server. type mcpPromptResultMsg struct { text string // concatenated user messages to submit as the prompt fileParts []kit.LLMFilePart // binary attachments from embedded resources err error // error from the server } // beforeSessionSwitchResultMsg carries the result of an asynchronously // executed before-session-switch hook. The hook runs in a goroutine so that // blocking operations like ctx.PromptConfirm() do not deadlock the TUI. type beforeSessionSwitchResultMsg struct { cancelled bool reason string initialPrompt string } // beforeForkResultMsg carries the result of an asynchronously executed // before-fork hook along with the fork context needed to complete the // operation if the hook allows it. type beforeForkResultMsg struct { cancelled bool reason string // Fork context — preserved so the operation can proceed after the hook. targetID string isUser bool userText string } // updatePromptState handles all messages while the prompt overlay is active. // It routes keys to the prompt overlay, detects completion/cancellation, and // restores the previous state when done. func (m *AppModel) updatePromptState(msg tea.Msg) (tea.Model, tea.Cmd) { var cmds []tea.Cmd switch msg := msg.(type) { case tea.KeyPressMsg: if msg.String() == "ctrl+c" { // Cancel the prompt but don't quit — let the main handler's // double-Ctrl+C logic handle quitting. m.resolvePrompt(app.PromptResponse{Cancelled: true}) // Don't consume the keypress — re-dispatch so the main // ctrl+c handler can track the double-press state. return m.Update(msg) } result, cmd := m.prompt.Update(msg) if cmd != nil { cmds = append(cmds, cmd) } if result != nil { if result.cancelled { m.resolvePrompt(app.PromptResponse{Cancelled: true}) } else { m.resolvePrompt(app.PromptResponse{ Value: result.value, Index: result.index, Values: result.values, Indices: result.indices, Confirmed: result.confirmed, }) } } case app.PromptRequestEvent: // Already handling a prompt — reject concurrent requests. if msg.ResponseCh != nil { msg.ResponseCh <- app.PromptResponse{Cancelled: true} } case app.PasswordPromptEvent: // A password prompt can't be shown while another prompt is active. // Reject immediately — dropping the event would leave the bash tool // (and the whole agent turn) blocked forever on the response channel. if msg.ResponseCh != nil { msg.ResponseCh <- app.PasswordPromptResponse{Cancelled: true} } case app.OverlayRequestEvent: // Can't show an overlay while a prompt is active — reject so the // requesting extension goroutine unblocks. if msg.ResponseCh != nil { msg.ResponseCh <- app.OverlayResponse{Cancelled: true} } case app.NewSessionRequestEvent: // Can't switch sessions while a prompt is active — fail the request // so the extension goroutine blocked on the response channel unblocks. if msg.ResponseCh != nil { msg.ResponseCh <- fmt.Errorf("cannot start a new session while a prompt is active") } case tea.WindowSizeMsg: m.width = msg.Width m.height = msg.Height m.notifyResize() _, cmd := m.prompt.Update(msg) if cmd != nil { cmds = append(cmds, cmd) } default: // Pass blink ticks and other messages to the prompt overlay. _, cmd := m.prompt.Update(msg) if cmd != nil { cmds = append(cmds, cmd) } } return m, tea.Batch(cmds...) } // resolvePrompt sends the response through the channel, clears prompt state, // and restores the previous app state. func (m *AppModel) resolvePrompt(resp app.PromptResponse) { if m.promptResponseCh != nil { m.promptResponseCh <- resp m.promptResponseCh = nil } m.prompt = nil m.state = m.prePromptState // The input area comes back. Measure the layout again. m.layoutDirty = true } // -------------------------------------------------------------------------- // Overlay dialog support // -------------------------------------------------------------------------- // updateOverlayState handles all messages while the overlay dialog is active. // It routes keys to the overlay, detects completion/cancellation, and restores // the previous state when done. func (m *AppModel) updateOverlayState(msg tea.Msg) (tea.Model, tea.Cmd) { var cmds []tea.Cmd switch msg := msg.(type) { case tea.KeyPressMsg: if msg.String() == "ctrl+c" { // Cancel the overlay but don't quit — let the main handler's // double-Ctrl+C logic handle quitting. m.resolveOverlay(app.OverlayResponse{Cancelled: true}) // Don't consume the keypress — re-dispatch so the main // ctrl+c handler can track the double-press state. return m.Update(msg) } result, cmd := m.overlay.Update(msg) if cmd != nil { cmds = append(cmds, cmd) } if result != nil { if result.cancelled { m.resolveOverlay(app.OverlayResponse{Cancelled: true}) } else { m.resolveOverlay(app.OverlayResponse{ Action: result.action, Index: result.index, }) } } case app.OverlayRequestEvent: // Already handling an overlay — reject concurrent requests. if msg.ResponseCh != nil { msg.ResponseCh <- app.OverlayResponse{Cancelled: true} } case app.PromptRequestEvent: // Can't show a prompt while an overlay is active — reject. if msg.ResponseCh != nil { msg.ResponseCh <- app.PromptResponse{Cancelled: true} } case app.PasswordPromptEvent: // Can't show a password prompt while an overlay is active. Reject // immediately — dropping the event would leave the bash tool (and // the whole agent turn) blocked forever on the response channel. if msg.ResponseCh != nil { msg.ResponseCh <- app.PasswordPromptResponse{Cancelled: true} } case app.NewSessionRequestEvent: // Can't switch sessions while an overlay is active — fail the request // so the extension goroutine blocked on the response channel unblocks. if msg.ResponseCh != nil { msg.ResponseCh <- fmt.Errorf("cannot start a new session while an overlay is active") } case tea.WindowSizeMsg: m.width = msg.Width m.height = msg.Height m.notifyResize() _, cmd := m.overlay.Update(msg) if cmd != nil { cmds = append(cmds, cmd) } case tea.MouseWheelMsg: // The overlay is modal, so the wheel belongs to it rather than to the // scrollback behind it. Without this the wheel silently scrolled the // transcript underneath a dialog the reader was trying to page through. _, cmd := m.overlay.Update(msg) if cmd != nil { cmds = append(cmds, cmd) } } return m, tea.Batch(cmds...) } // resolveOverlay sends the response through the channel, clears overlay state, // and restores the previous app state. func (m *AppModel) resolveOverlay(resp app.OverlayResponse) { if m.overlayResponseCh != nil { m.overlayResponseCh <- resp m.overlayResponseCh = nil } m.overlay = nil m.state = m.preOverlayState } // -------------------------------------------------------------------------- // Shell command execution (! and !!) // -------------------------------------------------------------------------- // shellCommandTimeout is the maximum duration for a user shell command. const shellCommandTimeout = 120 * time.Second // shellStreamBuffer is how many chunks may be waiting for the UI. // // It is a buffer and not a queue on purpose. A producer that waits for a slow // consumer stalls the command it is streaming, and a command that stalls mid-way // looks like a hang. Dropping a chunk costs the user one frame of output; // blocking costs them the command. The full text is collected by the runner // regardless, so the finished block is complete either way. const shellStreamBuffer = 256 // executeShellCommand appends a pending block to the transcript and returns the // commands that run the command and stream its output back. // // It is launched from Update as a tea.Cmd so the TUI stays responsive. func (m *AppModel) executeShellCommand(msg uicore.ShellCommandMsg) tea.Cmd { command := msg.Command excludeFromContext := msg.ExcludeFromContext cwd := m.cwd shell := m.shell // The block goes into the transcript immediately, before the command starts, // so the user sees what they asked for and not an empty gap while the // first bytes are still on their way. itemID := generateMessageID() item := NewShellRunItem(itemID, command, excludeFromContext) m.messages = append(m.messages, item) m.refreshContent() if m.scrollList != nil { m.scrollList.InvalidateItemHeight(itemID) } streamCh := make(chan string, shellStreamBuffer) onChunk := func(chunk string, _ bool) { select { case streamCh <- chunk: default: // The UI is behind. Drop this chunk; the next frame catches up. } } cmds := make([]tea.Cmd, 0, 2) // The reader pumps the channel into messages, one chunk per message, and // Update re-arms it each time. It is the only way to get bytes from a // running goroutine into Update without calling prog.Send from inside // Update itself, which deadlocks Bubble Tea's event loop. cmds = append(cmds, shellStreamReaderCmd(itemID, streamCh)) cmds = append(cmds, func() tea.Msg { result, err := core.RunShellCommand(context.Background(), core.ShellRunOptions{ Command: command, Shell: shell, WorkDir: cwd, Timeout: shellCommandTimeout, OnChunk: onChunk, }) // Closing ends the reader pump. It happens before the result is // returned so the final chunks are already in flight when Update sees // the result, and the block is filled in before it is settled. close(streamCh) if err != nil && !errors.Is(err, context.Canceled) { return uicore.ShellCommandResultMsg{ Command: command, Output: fmt.Sprintf("error: %v", err), ExitCode: -1, Err: err, ExcludeFromContext: excludeFromContext, ItemID: itemID, } } return uicore.ShellCommandResultMsg{ Command: command, Output: result.Output, ExitCode: result.ExitCode, ExcludeFromContext: excludeFromContext, ItemID: itemID, TimedOut: result.TimedOut, } }) return tea.Batch(cmds...) } // shellStreamReaderCmd returns a command that waits for one chunk on ch and // hands it to Update as a ShellStreamChunkMsg. // // Update re-arms the same command with the channel it gets back, so the pump // runs one chunk at a time and stops when the runner closes the channel. func shellStreamReaderCmd(itemID string, ch chan string) tea.Cmd { return func() tea.Msg { chunk, ok := <-ch if !ok { return nil } return uicore.ShellStreamChunkMsg{ItemID: itemID, Chunk: chunk, Ch: ch} } } // handleShellCommandChunk appends streamed output to the pending block and // re-arms the reader that feeds it. // // The chunk is raw. It is not normalized here: a chunk can end in the middle of // an escape sequence, and normalizing a partial chunk would drop the sequence // half of it forever. The block holds the raw bytes and normalizes the whole // buffer on each render, which repairs the split. func (m *AppModel) handleShellCommandChunk(msg uicore.ShellStreamChunkMsg) tea.Cmd { item := m.shellRunItem(msg.ItemID) if item != nil { item.AppendOutput(msg.Chunk) m.followShellRun(item.ID()) } if msg.Ch == nil { return nil } return shellStreamReaderCmd(msg.ItemID, msg.Ch) } // handleShellCommandResult settles the block for a command that has finished // and, for a `!` command, injects its output into the conversation so the model // can refer to it on the next turn. func (m *AppModel) handleShellCommandResult(msg uicore.ShellCommandResultMsg) tea.Cmd { item := m.shellRunItem(msg.ItemID) if item == nil { // No pending block to settle. The only way here is a result with no ID, // which no caller sends; append a finished block rather than dropping // the output, because losing a command's result is worse than an extra // block in the transcript. item = NewShellRunItem(generateMessageID(), msg.Command, msg.ExcludeFromContext) m.messages = append(m.messages, item) } switch { case msg.Err != nil && !msg.TimedOut: item.MarkFailed(fmt.Sprintf("error: %v", msg.Err)) case msg.TimedOut: item.MarkTimedOut(msg.Output) default: item.MarkComplete(msg.Output, msg.ExitCode) } m.refreshContent() m.followShellRun(item.ID()) // For ! (included in context): inject the command output into the // conversation as a user message so the LLM can reference it on the next // turn. This does NOT trigger an LLM response — it only adds to the // conversation history. if !msg.ExcludeFromContext && m.appCtrl != nil { m.appCtrl.AddContextMessage(shellContextMessage(msg)) } return nil } // shellContextMessage builds the conversation entry for a `!` command. // // The output is stripped of escape sequences first. The model reads text, and // a stream of colour codes is noise it can only misread — and it costs context // for every byte. Truncation keeps the tail, which is where the conclusion of // a command is. func shellContextMessage(msg uicore.ShellCommandResultMsg) string { output := style.StripForContext(msg.Output) if output == "" { output = "(no output)" } else { output = core.TruncateTail(output, core.DefaultMaxLines, core.DefaultMaxBytes).Content } status := fmt.Sprintf("%d", msg.ExitCode) if msg.TimedOut { status = "true" } return fmt.Sprintf("\n%s\n\n%s\n%s\n", msg.Command, output, status) } // shellRunItem finds the block for a shell run, or nil. func (m *AppModel) shellRunItem(id string) *ShellRunItem { if id == "" { return nil } for _, msg := range m.messages { if item, ok := msg.(*ShellRunItem); ok && item.ID() == id { return item } } return nil } // followShellRun drops the cached height of a shell block and keeps the // viewport pinned to the bottom, unless the user has taken the scroll position // or is mid-selection. // // Both exceptions matter. Scrolling during a stream is how a user reads // something above it, and yanking the viewport back fights them. Holding the // mouse button while the list moves is the copy-selection drift the streaming // path in appendStreamingChunk already guards against. func (m *AppModel) followShellRun(id string) { if m.scrollList == nil { return } m.scrollList.InvalidateItemHeight(id) if m.scrollList.IsMouseDown() { return } if m.scrollList.autoScroll || m.scrollList.AtBottom() { m.scrollList.autoScroll = true m.scrollList.GotoBottom() } } // computeGfxPlacement returns the escape sequence that redraws every // directly-placed image at its current position, or "" when there is nothing // to draw and nothing to take away. // // Direct placements are needed by terminals that carry the Kitty graphics // protocol but not its Unicode placeholder encoding, where an image is painted // over the screen at the cursor instead of travelling with the view text. That // makes an image's position a property of the finished layout, which is why // this runs from View with the assembled parts in hand. // // parts are the stacked layout sections; inputPartIndex is the position of the // input section within them and scrollPartIndex that of the transcript, or -1 // when the transcript is not on screen. // // Images that were painted by the previous frame and are not painted by this // one are deleted here. A placement outlives the cells it covers, so a preview // whose message has scrolled away, or which a modal now covers, has to be told // to go; everything still on screen drops its own earlier placement as part of // being drawn again. func (m *AppModel) computeGfxPlacement(parts []string, inputPartIndex, scrollPartIndex int) string { placements := m.composerPlacements(parts, inputPartIndex) placements = append(placements, m.transcriptPlacements(parts, scrollPartIndex)...) placements = append(placements, m.imagePreviewPlacement()...) var draw strings.Builder drawn := make(map[uint32]struct{}, len(placements)) for _, p := range placements { if p.row < 1 || p.row > m.height { continue // scrolled out of the visible area } draw.WriteString(ansi.CursorPosition(p.col, p.row)) draw.WriteString(p.seq) if p.id != 0 { drawn[p.id] = struct{}{} } } if m.gfxPendingDrops == nil { m.gfxPendingDrops = make(map[uint32]struct{}) } for id := range m.gfxPlaced { if _, ok := drawn[id]; !ok { m.gfxPendingDrops[id] = struct{}{} } } var drops strings.Builder for id := range m.gfxPendingDrops { if _, ok := drawn[id]; ok { delete(m.gfxPendingDrops, id) continue } drops.WriteString(imagepreview.DeletePlacements(id)) } m.gfxPlaced = drawn if draw.Len() == 0 { // Deleting a placement does not depend on the cursor, so the sequence // that only removes images needs no cursor dance around it. return drops.String() } // Save the cursor, draw each image at its absolute row, then restore. The // renderer owns the cursor; moving it without putting it back would leave // the next frame drawing in the wrong place. return ansi.SaveCursor + draw.String() + ansi.RestoreCursor + drops.String() } // gfxPlacement is one image drawn at an absolute position on the screen. type gfxPlacement struct { // row and col are 1-based screen coordinates of the image's top-left cell. row, col int // id is the terminal's id for the image, or 0 when the caller frees the // image itself and does not want its placement tracked. id uint32 // seq draws the image at the cursor. seq string } // composerPlacements locates the directly-placed preview images in the // composer. // // The rows are counted up from the bottom of the screen, not down from the // top. The composer sits at the bottom with only the status bar and an // optional footer beneath it, so counting upwards depends on a couple of // short, fixed sections. Counting downwards would instead depend on the // scrollback's rendered height, and any disagreement between what it was // allotted and what it drew would float the image away from the composer. // // The input component owns image data; the parent tracks placements so it can // hide images behind overlays without deleting their data. func (m *AppModel) composerPlacements(parts []string, inputPartIndex int) []gfxPlacement { // Direct placements do not participate in cell-level composition. Hide // composer images while a modal or autocomplete popup is active, just as // transcript images are hidden, or they can paint over the overlay. if m.modalActive() { return nil } ic, ok := m.input.(*InputComponent) if !ok || inputPartIndex < 0 || inputPartIndex >= len(parts) { return nil } placements := ic.DirectPlacements() if len(placements) == 0 { return nil } // Rows occupied by everything below the input section. below := 0 for i := inputPartIndex + 1; i < len(parts); i++ { below += lipgloss.Height(parts[i]) } // Screen rows are 1-based, so the input's last row is m.height-below and // its first row is that many rows further up. inputTop := m.height - below - lipgloss.Height(parts[inputPartIndex]) + 1 out := make([]gfxPlacement, 0, len(placements)) for _, p := range placements { out = append(out, gfxPlacement{ row: inputTop + p.RowOffset, col: p.Col + 1, id: p.ImageID, seq: p.Sequence, }) } return out } // transcriptPlacements locates the directly-placed images in the scrollback, // clipped to the rows the viewport currently shows. // // Unlike the composer, the transcript scrolls, so an image here is a moving // target: its rows are whatever the list draws for its item this frame, and // only the visible band of the picture may be painted. Anything more would // spill over the message above or the composer below, because a placed image // is not part of the view and nothing clips it. // // The rows are counted down from the top of the screen, which for the // transcript depends only on the optional header above it. Counting up would // depend on every section below, of which there are many. func (m *AppModel) transcriptPlacements(parts []string, scrollPartIndex int) []gfxPlacement { if m.scrollList == nil || scrollPartIndex < 0 || scrollPartIndex >= len(parts) { return nil } // A modal covers the transcript, and an image painted over it would be the // one thing on screen that the dialog could not hide. Returning nothing // takes the images off screen for as long as the modal is up; they come // back on the frame that closes it. if m.modalActive() { return nil } // Nothing is placed and nothing could be: skip the walk over visible items // entirely in the terminals where previews are text. if len(m.gfxPlaced) == 0 && termgfx.PreviewMode() != termgfx.ModeDirect { return nil } // The transcript's first screen row, 1-based. top := 1 for i := range scrollPartIndex { top += lipgloss.Height(parts[i]) } var out []gfxPlacement for _, vis := range m.scrollList.VisibleItems() { item, ok := vis.Item.(DirectImageItem) if !ok { continue } thumb, ok := item.DirectImage() if !ok { continue } // Where the picture sits inside its own item. Message navigation frames // the selected item, which moves its content one row down and one // column right. imgTop, imgCol := 0, style.ContentOffset if vis.Framed { imgTop, imgCol = 1, style.ContentOffset+1 } // Intersect the item's drawn lines with the lines the picture occupies. first := max(vis.SkipTop, imgTop) last := min(vis.SkipTop+vis.Height, imgTop+thumb.Rows) if last <= first { continue } seq := thumb.PlaceRows(first-imgTop, last-first) if seq == "" { continue } out = append(out, gfxPlacement{ row: top + vis.Row + (first - vis.SkipTop), col: imgCol + 1, id: thumb.ImageID, seq: seq, }) } return out } // handleKeyPress routes a key through the app before the focused child. func (m *AppModel) handleKeyPress(msg tea.KeyPressMsg, cmds []tea.Cmd, previewCleanup tea.Cmd) (tea.Model, tea.Cmd) { // Clear any active mouse selection on keypress. if m.scrollList.HasSelection() { m.scrollList.ClearSelection() } switch { case key.Matches(msg, keys.Interrupt): // Cancel any active prompt before quitting. if m.promptResponseCh != nil { m.promptResponseCh <- app.PromptResponse{Cancelled: true} m.promptResponseCh = nil m.prompt = nil } // Cancel any active overlay before quitting. if m.overlayResponseCh != nil { m.overlayResponseCh <- app.OverlayResponse{Cancelled: true} m.overlayResponseCh = nil m.overlay = nil } // Second Ctrl+C within the timeout window — quit. if m.ctrlCPressedOnce { m.quitting = true if previewCleanup != nil { return m, tea.Sequence(previewCleanup, tea.Quit) } return m, tea.Quit } // First Ctrl+C — clear input if it has content, then arm the quit flag. if m.state == stateInput { if ic, ok := m.input.(*InputComponent); ok { ic.Clear() } } m.ctrlCPressedOnce = true // Start reset timer so the flag clears after 3 seconds. if previewCleanup != nil { return m, tea.Sequence(previewCleanup, ctrlCResetCmd()) } return m, ctrlCResetCmd() } if m.subagentRunPickerOpen() { _, cmd := m.subagentRunPicker.Update(msg) return m, tea.Batch(append(cmds, cmd)...) } // Route to the /kill-subagent picker when open. It owns the keyboard // (including esc, which closes it instead of cancelling the turn). if m.killSubagentOpen() { _, cmd := m.killSubagentSelector.Update(msg) cmds = append(cmds, cmd) return m, tea.Batch(cmds...) } // Check extension-registered global keyboard shortcuts. These fire // in all app states except modal prompts/overlays (which return early // above) and message navigation, which rebinds plain keys like j/k // and enter for itself — an extension shortcut on one of those would // otherwise consume it first and silently break navigation. // // An armed leader chord (Ctrl+X) also takes precedence: the chord owns // the next key press outright. Without this guard a shortcut bound to // a chord suffix (s/t/m/e) stole the key and returned early, leaving // leaderKeyActive latched on forever. // // Matched shortcuts are consumed — the key does not propagate // to child components. if key.Matches(msg, keys.SubagentRuns) && (m.state == stateInput || m.state == stateWorking) && !m.modalActive() && !m.leaderKeyActive { m.openSubagentRunPicker() return m, tea.Batch(cmds...) } if m.getGlobalShortcuts != nil && m.state != stateMessageNav && !m.leaderKeyActive { if shortcuts := m.getGlobalShortcuts(); shortcuts != nil { if handler, ok := lookupShortcut(shortcuts, msg); ok { // Run in goroutine so blocking extension calls // (PromptSelect, etc.) don't stall the event loop. go handler() return m, tea.Batch(cmds...) } } } if cmd, handled := m.handleScrollbackKey(msg); handled { return m, tea.Batch(append(cmds, cmd)...) } if cmd, handled := m.handleThinkingKey(msg); handled { return m, tea.Batch(append(cmds, cmd)...) } if cmd, handled := m.routeOverlayKey(msg); handled { return m, tea.Batch(append(cmds, cmd)...) } if cmd, handled := m.handleMessageNavKey(msg); handled { return m, tea.Batch(append(cmds, cmd)...) } if cmd, handled := m.handleLeaderChord(msg); handled { return m, tea.Batch(append(cmds, cmd)...) } // Route key events to the focused child. Check for editor // interceptor first — it can consume, remap, or force-submit keys. if m.input != nil { var intercepted bool if m.getEditorInterceptor != nil { if interceptor := m.getEditorInterceptor(); interceptor != nil && interceptor.HandleKey != nil { var currentText string if ic, ok := m.input.(*InputComponent); ok { currentText = ic.textarea.Value() } action := interceptor.HandleKey(msg.String(), currentText) switch action.Type { case EditorKeyConsumed: intercepted = true case EditorKeyRemap: if remapped, ok := remapKey(action.RemappedKey); ok { updated, cmd := m.input.Update(remapped) m.input, _ = updated.(inputComponentIface) cmds = append(cmds, cmd) m.syncInputHeight() intercepted = true } // If remap target is unrecognized, fall through to normal handling. case EditorKeySubmit: text := action.SubmitText var images []uicore.ImageAttachment if text == "" { if ic, ok := m.input.(*InputComponent); ok { text = strings.TrimSpace(ic.textarea.Value()) var cleanup tea.Cmd images, cleanup = ic.ClearPendingImages() if cleanup != nil { cmds = append(cmds, cleanup) } ic.textarea.SetValue("") ic.textarea.CursorEnd() } } if text != "" { cmds = append(cmds, func() tea.Msg { return uicore.SubmitMsg{Text: text, Images: images} }) } intercepted = true } // EditorKeyPassthrough falls through to normal input handling. } } if !intercepted { updated, cmd := m.input.Update(msg) m.input, _ = updated.(inputComponentIface) cmds = append(cmds, cmd) // The composer is dynamically sized, so a keystroke that wraps // or unwraps a line changes how much room the transcript has. m.syncInputHeight() } } return m, tea.Batch(cmds...) } func (m *AppModel) handleScrollbackKey(msg tea.KeyPressMsg) (tea.Cmd, bool) { // Scrollback keybindings (PgUp/PgDn/Ctrl+Home/Ctrl+End) for navigating // message history. Active while the agent works too: a long turn is // exactly when the user wants to read back, and the mouse wheel // already scrolls in that state. Scrolling up clears autoScroll, so // streamed output does not pull the view back to the bottom. if m.state == stateInput || m.state == stateWorking { switch { case key.Matches(msg, keys.PageUp): m.scrollList.ScrollBy(-m.scrollList.height) m.scrollList.autoScroll = false return nil, true case key.Matches(msg, keys.PageDown): m.scrollList.ScrollBy(m.scrollList.height) if m.scrollList.AtBottom() { m.scrollList.autoScroll = true } return nil, true case key.Matches(msg, keys.Top): m.scrollList.GotoTop() m.scrollList.autoScroll = false return nil, true case key.Matches(msg, keys.Bottom): m.scrollList.GotoBottom() m.scrollList.autoScroll = true return nil, true } } return nil, false } func (m *AppModel) handleThinkingKey(msg tea.KeyPressMsg) (tea.Cmd, bool) { // Thinking keybindings — only when the model supports reasoning. // Note: thinking visibility toggle is under leader chord (Ctrl+X t) // to avoid conflicts with terminal multiplexers. if m.isReasoningModel { if key.Matches(msg, keys.CycleThinking) { // Cycle thinking level. m.cycleThinkingLevel() return nil, true } } return nil, false } func (m *AppModel) routeOverlayKey(msg tea.KeyPressMsg) (tea.Cmd, bool) { // Route to tree selector when active. if m.state == stateTreeSelector && m.treeSelector != nil { updated, cmd := m.treeSelector.Update(msg) m.treeSelector = updated.(*TreeSelectorComponent) return cmd, true } // Route to model selector when active. if m.state == stateModelSelector && m.modelSelector != nil { updated, cmd := m.modelSelector.Update(msg) m.modelSelector = updated.(*ModelSelectorComponent) return cmd, true } // Route to thinking-level selector when active. if m.state == stateThinkingLevelSelector && m.thinkingLevelSelector != nil { updated, cmd := m.thinkingLevelSelector.Update(msg) m.thinkingLevelSelector = updated.(*ThinkingLevelSelectorComponent) return cmd, true } if m.state == stateModelModeSelector && m.modelModeSelector != nil { updated, cmd := m.modelModeSelector.Update(msg) m.modelModeSelector = updated.(*ModelModeSelectorComponent) return cmd, true } // Route to theme selector when active. if m.state == stateThemeSelector && m.themeSelector != nil { updated, cmd := m.themeSelector.Update(msg) m.themeSelector = updated.(*ThemeSelectorComponent) return cmd, true } // Route to the /connect dialog when active. if m.state == stateProviderConnect && m.providerConnect != nil { updated, cmd := m.providerConnect.Update(msg) m.providerConnect = updated.(*ProviderConnectComponent) return cmd, true } // Route to session selector when active. if m.state == stateSessionSelector && m.sessionSelector != nil { updated, cmd := m.sessionSelector.Update(msg) m.sessionSelector = updated.(*SessionSelectorComponent) return cmd, true } return nil, false } func (m *AppModel) handleMessageNavKey(msg tea.KeyPressMsg) (tea.Cmd, bool) { // Message navigation consumes every key it understands so the // composer never sees j/k as text while the user is browsing. if m.state == stateMessageNav { // Any navigation key retires the previous acknowledgement, except // the one that produces a fresh copy. if !key.Matches(msg, keys.NavCopy) { m.navNotice = "" } switch { case key.Matches(msg, keys.NavUp): m.moveMessageSelection(-1) return nil, true case key.Matches(msg, keys.NavDown): m.moveMessageSelection(1) return nil, true case key.Matches(msg, keys.NavFirst): if idx := m.firstSelectableIndex(); idx >= 0 { m.selectMessage(idx) } return nil, true case key.Matches(msg, keys.NavLast): if idx := m.lastSelectableIndex(); idx >= 0 { m.selectMessage(idx) } return nil, true // Jump between the user's own turns. "Scroll back to what I asked" // is the dominant reason to enter navigation at all, and stepping // there one tool result at a time is a lot of keypresses. case key.Matches(msg, keys.NavPrevUser): m.jumpToRole("user", -1) return nil, true case key.Matches(msg, keys.NavNextUser): m.jumpToRole("user", 1) return nil, true case key.Matches(msg, keys.NavCopy): return m.copySelectedMessage(), true case key.Matches(msg, keys.NavOpen): // A shell block expands in place rather than opening the // inspector: the whole point is to read the output where the // conversation is, with the rest of the turn still in view. // Every other item opens the inspector, which is what the frame // hint advertises. if item := m.selectedShellRun(); item != nil && !item.Spinning() { m.toggleShellRunExpansion(item) return nil, true } m.inspectSelectedMessage() return nil, true case key.Matches(msg, keys.NavExpand): if item := m.selectedShellRun(); item != nil { m.toggleShellRunExpansion(item) return nil, true } case key.Matches(msg, keys.NavLeft): m.scrollSelectedShellRun(-1) return nil, true case key.Matches(msg, keys.NavRight): m.scrollSelectedShellRun(1) return nil, true case key.Matches(msg, keys.NavExit): m.exitMessageNav() return nil, true } // Swallow everything else: an unhandled key must not leak into // the composer while navigation owns the keyboard. return nil, true } return nil, false } func (m *AppModel) handleLeaderChord(msg tea.KeyPressMsg) (tea.Cmd, bool) { var cmds []tea.Cmd // ── Leader key chord handling (Ctrl+X prefix) ────────────── // If the leader key was previously pressed, the current key // completes the chord. We consume it regardless of match so // the prefix doesn't leak to child components. if m.leaderKeyActive { m.leaderKeyActive = false switch { case key.Matches(msg, keys.Steer): // Ctrl+X s → Steer: inject the current input as a steering // message into the running agent turn. if m.state == stateWorking && m.appCtrl != nil { var text string if ic, ok := m.input.(*InputComponent); ok { text = strings.TrimSpace(ic.textarea.Value()) } if text != "" { // Clear the input, collect pending images, and push to history. var images []uicore.ImageAttachment if ic, ok := m.input.(*InputComponent); ok { ic.pushHistory(text) ic.textarea.SetValue("") var cleanup tea.Cmd images, cleanup = ic.ClearPendingImages() if cleanup != nil { cmds = append(cmds, cleanup) } } // Preprocess @file references (text files are XML-inlined, // binary files are extracted as multimodal parts). processedText := text var fileParts []kit.LLMFilePart if m.cwd != "" { result := fileutil.ProcessFileAttachments(text, m.cwd, m.mcpResourceReader) processedText = result.ProcessedText for _, fp := range result.FileParts { fileParts = append(fileParts, kit.LLMFilePart{ Filename: fp.Filename, Data: fp.Data, MediaType: fp.MediaType, }) } } // Convert clipboard image attachments to kit.LLMFilePart. for _, img := range images { fileParts = append(fileParts, kit.LLMFilePart{ Data: img.Data, MediaType: img.MediaType, }) } // Build display text (include image count if any). displayText := text if len(images) > 0 { displayText = fmt.Sprintf("%s\n[%d image(s) attached]", text, len(images)) } // Inject the steer message. sLen := m.appCtrl.SteerWithFiles(processedText, fileParts) if sLen > 0 { m.steeringMessages = append(m.steeringMessages, displayText) m.layoutDirty = true } else { // Started immediately (agent was idle). m.pendingUserPrints = append(m.pendingUserPrints, displayText) m.flushStreamAndPendingUserMessages() if !m.agentWorking() { m.setAgentState(stateWorking) } } } } case key.Matches(msg, keys.ToggleThinking): // Ctrl+X t → Toggle thinking block visibility. if m.isReasoningModel { m.thinkingVisible = !m.thinkingVisible for _, p := range m.allPanes() { if p.stream != nil { p.stream.SetThinkingVisible(m.thinkingVisible) } } } case key.Matches(msg, keys.MessageNav): // Ctrl+X m → Move: navigate messages in the scrollback. m.enterMessageNav() case key.Matches(msg, keys.ExternalEditor): // Ctrl+X e → open $EDITOR to compose/edit the prompt. editorApp := os.Getenv("VISUAL") if editorApp == "" { editorApp = os.Getenv("EDITOR") } if editorApp == "" { m.printSystemMessage("Set `$EDITOR` or `$VISUAL` to use external editor") } else { var currentText string if ic, ok := m.input.(*InputComponent); ok { currentText = ic.textarea.Value() } tmpFile, err := os.CreateTemp("", "kit_prompt_*.md") if err == nil { if currentText != "" { _, _ = tmpFile.WriteString(currentText) } _ = tmpFile.Close() editorCmd, cmdErr := editor.Command(editorApp, tmpFile.Name()) if cmdErr != nil { _ = os.Remove(tmpFile.Name()) m.printSystemMessage(fmt.Sprintf("Failed to open editor: %v", cmdErr)) } else { cmds = append(cmds, tea.ExecProcess(editorCmd, func(err error) tea.Msg { if err != nil { _ = os.Remove(tmpFile.Name()) return externalEditorMsg{err: err} } content, readErr := os.ReadFile(tmpFile.Name()) _ = os.Remove(tmpFile.Name()) if readErr != nil { return externalEditorMsg{err: readErr} } return externalEditorMsg{text: string(content)} })) } } } } // Chord consumed — don't propagate to children. return tea.Batch(cmds...), true } switch { case key.Matches(msg, keys.Cancel): if m.state == stateWorking { if m.canceling { // Second ESC within the timer window — cancel the step. m.canceling = false if m.appCtrl != nil { m.appCtrl.CancelCurrentStep() } } else { // First ESC — set canceling, start 2s timer. m.canceling = true cmds = append(cmds, cancelTimerCmd()) } return tea.Batch(cmds...), true } // In other states pass ESC through to children below. case key.Matches(msg, keys.Leader): // Activate leader key prefix — the next keypress completes the chord. m.leaderKeyActive = true return tea.Batch(cmds...), true } return nil, false } // handleSubmit processes commands and forwards prompts to the app layer. func (m *AppModel) handleSubmit(msg uicore.SubmitMsg, cmds []tea.Cmd) (tea.Model, tea.Cmd) { // Re-enable auto-scroll when user submits a new message. m.scrollList.autoScroll = true // Reset Ctrl+C flag so next Ctrl+C clears input instead of quitting. m.ctrlCPressedOnce = false // Handle slash commands locally — they should never reach app.Run(). // Parse once: split on the first space so argument-bearing commands // (e.g. "/model anthropic/foo", "/compact Focus on X") are matched by // their name and their args are passed through to the handler. if strings.HasPrefix(msg.Text, "/") { name, args, _ := strings.Cut(msg.Text, " ") if sc := commands.GetCommandByName(name); sc != nil { if cmd := m.handleSlashCommand(sc, strings.TrimSpace(args)); cmd != nil { cmds = append(cmds, cmd) } return m, tea.Batch(cmds...) } } // Check extension-registered slash commands. These support arguments // (e.g. "/sub list files"), so we split on the first space. if cmd := m.handleExtensionCommand(msg.Text); cmd != nil { cmds = append(cmds, cmd) return m, tea.Batch(cmds...) } // Check MCP prompt commands (/: [args]). if cmd := m.handleMCPPromptCommand(msg.Text); cmd != nil { cmds = append(cmds, cmd) return m, tea.Batch(cmds...) } // Expand prompt templates. If the input matches a template name, // substitute arguments and use the expanded content as the prompt. if expanded, ok, validationErr := m.expandPromptTemplate(msg.Text); validationErr != "" { // Validation failed — re-populate the input so the user can // append the missing arguments without retyping. if ic, ok := m.input.(*InputComponent); ok { ic.textarea.SetValue(msg.Text + " ") ic.textarea.CursorEnd() } return m, tea.Batch(cmds...) } else if ok { msg.Text = expanded } // No usable provider: do not send the prompt, tell the user how to // fix it (mirrors opencode's "Connect a provider to send prompts"). if m.providerError != nil { m.printSystemMessage(m.providerErrorNotice()) if ic, ok := m.input.(*InputComponent); ok { ic.textarea.SetValue(msg.Text) ic.textarea.CursorEnd() } return m, tea.Batch(cmds...) } // Regular prompt — forward to the app layer. // Preprocess @file references: text files are XML-inlined, binary files // (images, audio, etc.) are extracted as multimodal parts. The display // text (shown in ScrollList) uses the original user text so the UI stays clean. processedText := msg.Text var fileParts []kit.LLMFilePart if m.cwd != "" { result := fileutil.ProcessFileAttachments(msg.Text, m.cwd, m.mcpResourceReader) processedText = result.ProcessedText for _, fp := range result.FileParts { fileParts = append(fileParts, kit.LLMFilePart{ Filename: fp.Filename, Data: fp.Data, MediaType: fp.MediaType, }) } } // Convert clipboard image attachments to kit.LLMFilePart. fileOnlyCount := len(fileParts) // binary @file parts (before clipboard images) for _, img := range msg.Images { fileParts = append(fileParts, kit.LLMFilePart{ Data: img.Data, MediaType: img.MediaType, }) } // Build display text for ScrollList (include attachment counts). displayText := msg.Text if len(msg.Images) > 0 || fileOnlyCount > 0 { var badges []string if len(msg.Images) > 0 { badges = append(badges, fmt.Sprintf("%d image(s) pasted", len(msg.Images))) } if fileOnlyCount > 0 { badges = append(badges, fmt.Sprintf("%d file(s) attached", fileOnlyCount)) } displayText = fmt.Sprintf("%s\n[%s]", msg.Text, strings.Join(badges, ", ")) } if m.appCtrl != nil { // Run returns the queue depth: >0 means the prompt was queued // (agent is busy). We update queuedMessages directly here // instead of relying on an event from prog.Send(), which would // deadlock when called synchronously from within Update(). var qLen int if len(fileParts) > 0 { qLen = m.appCtrl.RunWithFiles(processedText, fileParts) } else { qLen = m.appCtrl.Run(processedText) } if qLen > 0 { // Queued: anchor the message text above the input with a // "queued" badge. It will be added to the ScrollList when // the agent picks it up (via SpinnerEvent). m.queuedMessages = append(m.queuedMessages, displayText) m.layoutDirty = true } else { // Started immediately. Flush any leftover stream content // from the previous step first, then print the user // message — combined via the ScrollList so // messages stay in chronological order. m.pendingUserPrints = append(m.pendingUserPrints, displayText) m.flushStreamAndPendingUserMessages() // Insert inline thumbnail previews after the user message. cmds = append(cmds, m.transcriptPreviewCmd(msg.Images, m.lastMessageID())) } } else { m.printUserMessage(displayText) // Insert inline thumbnail previews after the user message. cmds = append(cmds, m.transcriptPreviewCmd(msg.Images, m.lastMessageID())) } if !m.agentWorking() { m.setAgentState(stateWorking) } return m, tea.Batch(cmds...) } // handleAppMessage dispatches app events and forwards other messages to children. func (m *AppModel) handleAppMessage(msg tea.Msg, cmds []tea.Cmd) (tea.Model, tea.Cmd) { switch msg := msg.(type) { // ── App layer events ───────────────────────────────────────────────────── case app.SpinnerEvent: // SpinnerEvent{Show: true} means a new agent step has started (either // freshly or from the queue after a previous step completed). Flush // any leftover stream content from the previous step to the ScrollList // before starting the new one, followed by any pending user messages // from the queue. Everything goes through the ScrollList to // guarantee chronological ordering. if msg.Show { m.flushStreamAndPendingUserMessages() m.setAgentState(stateWorking) m.layoutDirty = true } cmds = append(cmds, m.applyPaneEvent(msg)) case app.ReasoningChunkEvent, app.ReasoningCompleteEvent, app.StreamChunkEvent, app.ToolCallStartedEvent, app.ToolExecutionEvent, app.ToolResultEvent, app.ToolOutputEvent: // Transcript and activity-row events. The subagent panes apply the // same events with the same function. cmds = append(cmds, m.applyPaneEvent(msg.(app.Event))) case app.ToolCallContentEvent: // In streaming mode this text was already delivered via StreamChunkEvents // and will be flushed before the next tool call. Ignore to avoid // double-printing. case app.RetryEvent, app.StepStartedEvent, app.StepResumeEvent, app.ResponseCompleteEvent: cmds = append(cmds, m.applyPaneEvent(msg.(app.Event))) case app.MessageCreatedEvent: // Informational — no action needed by parent. case app.QueueUpdatedEvent: // drainQueue popped item(s) from the queue. Move consumed // messages to pendingUserPrints — they will be printed to // the ScrollList in the next SpinnerEvent{Show: true} after the // previous assistant response is flushed. for len(m.queuedMessages) > msg.Length { text := m.queuedMessages[0] m.queuedMessages[0] = "" // release the string in the backing array for GC m.queuedMessages = m.queuedMessages[1:] m.pendingUserPrints = append(m.pendingUserPrints, text) } m.layoutDirty = true case app.SteerConsumedEvent: // Steering messages were consumed — either injected mid-turn via // PrepareStep, or drained into the queue after a text-only turn. // // Two cases: // // 1. Mid-turn (stateWorking, PrepareStep fired): no SpinnerEvent{Show: // true} will follow within this turn, so we cannot rely on // flushStreamAndPendingUserMessages() being called. Flush any live // stream content first (assistant text up to the steer point), then // render the steering user messages immediately to the ScrollList. // // 2. Post-turn (text-only response, drained after StepComplete): a // SpinnerEvent{Show: true} for the next turn is already in flight. // Defer to pendingUserPrints so the previous assistant response is // flushed first, preserving chronological order. if m.agentWorking() { // Case 1: mid-turn — flush + print immediately. m.flushStreamContent() for _, text := range m.steeringMessages { m.printUserMessage(text) } m.steeringMessages = m.steeringMessages[:0] m.layoutDirty = true } else { // Case 2: post-turn — defer so SpinnerEvent orders correctly. m.pendingUserPrints = append(m.pendingUserPrints, m.steeringMessages...) m.steeringMessages = m.steeringMessages[:0] m.layoutDirty = true } case app.StepCompleteEvent, app.StepCancelledEvent, app.StepErrorEvent: // The pane freezes the streamed response and prints the error block // (if any) and the turn receipt; then the composer gets focus again. cmds = append(cmds, m.applyPaneEvent(msg.(app.Event))) m.setAgentState(stateInput) m.canceling = false case app.CompactCompleteEvent: // Finalize any streaming compaction content. if m.stream != nil { m.stream.Reset() } m.setAgentState(stateInput) // Mark the last streaming message as complete in ScrollList. if len(m.messages) > 0 { if streamMsg, ok := m.messages[len(m.messages)-1].(*StreamingMessageItem); ok { streamMsg.MarkComplete() } } // Refresh content to show the finalized message. m.refreshContent() // Reset context token display — the pre-compaction count is stale. // The next API call will set the accurate post-compaction value. if m.usageTracker != nil { m.usageTracker.SetContextTokens(0) } // Print stats as a separate system message. saved := msg.OriginalTokens - msg.CompactedTokens statsMsg := fmt.Sprintf( "Compaction complete: %d messages summarised, ~%dk tokens freed (%dk -> %dk)", msg.MessagesRemoved, saved/1000, msg.OriginalTokens/1000, msg.CompactedTokens/1000, ) m.printSystemMessage(statsMsg) case app.CompactErrorEvent: if m.stream != nil { m.stream.Reset() } m.setAgentState(stateInput) m.printSystemMessage(fmt.Sprintf("Compaction failed: %v", msg.Err)) case app.ModelChangedEvent: // Extension changed the model — update display name in status bar // and message attribution. m.providerName = msg.ProviderName m.modelName = msg.ModelName case app.UsageUpdatedEvent: // Token usage was updated after a completed LLM step. No state // changes needed — the UsageTracker was already mutated in-place. // Returning from Update() triggers View() which re-renders the // status bar with the latest token counts, cost, and context %. case app.ThemeChangedEvent: // The theme was replaced from outside the /theme command (an // extension's ctx.SetTheme). The global theme is already set; this // repaints the components that cache styling derived from it. m.refreshTheme() case app.WidgetUpdateEvent: // Extension widget changed — recalculate height distribution so the // stream region accounts for widget space. View() will read the // latest widget state on the next render. m.layoutDirty = true // Refresh extension commands (e.g. after hot-reload). The callback // returns the current set from the runner which may have changed. if m.getExtensionCommands != nil { newCmds := m.getExtensionCommands() m.extensionCommands = newCmds if ic, ok := m.input.(*InputComponent); ok { // Remove old extension commands and add fresh ones. var builtins []commands.SlashCommand for _, sc := range ic.commands { if sc.Category != "Extensions" { builtins = append(builtins, sc) } } for _, ec := range newCmds { builtins = append(builtins, commands.SlashCommand{ Name: ec.Name, Description: ec.Description, Category: "Extensions", Complete: ec.Complete, }) } ic.commands = builtins } } case app.ContentReloadEvent: // Prompt templates or skills changed on disk — refresh from providers. m.refreshPromptTemplates() m.refreshSkillItems() m.printSystemMessage("Prompts and skills reloaded.") case app.MCPServerLoadedEvent: // An extension that prints its own summary of the servers can hide // the message for each server that loaded, but not a failure. if msg.Error == nil && m.uiVis().HideMCPStartupMessages { break } // A single MCP server finished loading — display a system message. if msg.Error != nil { m.printSystemMessage(fmt.Sprintf("MCP server '%s' failed to load: %v", msg.ServerName, msg.Error)) } else if msg.ToolCount > 0 { m.printSystemMessage(fmt.Sprintf("MCP server '%s' loaded with %d tools", msg.ServerName, msg.ToolCount)) } else { m.printSystemMessage(fmt.Sprintf("MCP server '%s' loaded (no tools)", msg.ServerName)) } case app.EditorTextSetEvent: // Extension wants to pre-fill the input editor with text. if ic, ok := m.input.(*InputComponent); ok { ic.textarea.SetValue(msg.Text) ic.textarea.CursorEnd() } case app.NewSessionRequestEvent: // Extension wants to end the current session and start a fresh // one (with an optional initial prompt). Stash the response // channel so performNewSession (or the before-hook cancellation // path) can signal completion, then run the same /new pipeline // the user would trigger. if msg.ResponseCh != nil { // Only one new-session request in flight at a time. If a // previous response channel is still pending, fail it before // replacing it so the prior extension goroutine unblocks. if m.newSessionResultCh != nil { m.newSessionResultCh <- fmt.Errorf("superseded by a newer NewSession request") } m.newSessionResultCh = msg.ResponseCh } if cmd := m.handleNewCommand(msg.InitialPrompt); cmd != nil { cmds = append(cmds, cmd) } case app.PasswordPromptEvent: // Sudo password prompt - show a modal input prompt // If already in prompt state, cancel the new request if m.state == statePrompt { if msg.ResponseCh != nil { msg.ResponseCh <- app.PasswordPromptResponse{Cancelled: true} } return m, tea.Batch(cmds...) } m.prePromptState = m.state m.state = statePrompt // Create a custom response channel that converts PasswordPromptResponse passwordResponseCh := make(chan app.PromptResponse, 1) m.promptResponseCh = passwordResponseCh // Create password input prompt (masked input) m.prompt = newPasswordPrompt(msg.Prompt, m.width, m.height) // Handle the response conversion go func() { resp := <-passwordResponseCh if msg.ResponseCh != nil { msg.ResponseCh <- app.PasswordPromptResponse{ Password: resp.Value, Cancelled: resp.Cancelled, } } }() if m.prompt != nil { cmds = append(cmds, m.prompt.Init()) } // The prompt replaces the input area and is taller. Measure the // layout again, or the terminal does not show its last lines. m.layoutDirty = true case app.PromptRequestEvent: // Extension wants to show an interactive prompt. Enter prompt state. // If already in prompt state (concurrent prompt from another // extension), immediately cancel the new request. if m.state == statePrompt { if msg.ResponseCh != nil { msg.ResponseCh <- app.PromptResponse{Cancelled: true} } return m, tea.Batch(cmds...) } m.prePromptState = m.state m.state = statePrompt m.promptResponseCh = msg.ResponseCh switch msg.PromptType { case "select": m.prompt = newSelectPrompt(msg.Message, msg.Options, m.width, m.height) case "multiselect": m.prompt = newMultiSelectPrompt(msg.Message, msg.Options, msg.DefaultSelected, m.width, m.height) case "confirm": defaultVal := msg.Default == "true" m.prompt = newConfirmPrompt(msg.Message, defaultVal, m.width, m.height) case "input": m.prompt = newInputPrompt(msg.Message, msg.Placeholder, msg.Default, m.width, m.height) default: // Unknown prompt type — cancel immediately. if msg.ResponseCh != nil { msg.ResponseCh <- app.PromptResponse{Cancelled: true} } m.state = m.prePromptState m.promptResponseCh = nil return m, tea.Batch(cmds...) } if m.prompt != nil { cmds = append(cmds, m.prompt.Init()) } // The prompt replaces the input area and is taller. Measure the // layout again, or the terminal does not show its last lines. m.layoutDirty = true case app.OverlayRequestEvent: // Extension wants to show a modal overlay dialog. Enter overlay state. // If already in overlay or prompt state, immediately cancel the request. if m.state == stateOverlay || m.state == statePrompt { if msg.ResponseCh != nil { msg.ResponseCh <- app.OverlayResponse{Cancelled: true} } return m, tea.Batch(cmds...) } m.preOverlayState = m.state m.state = stateOverlay m.overlayResponseCh = msg.ResponseCh m.overlay = newOverlayDialog( msg.Title, msg.Content, msg.Markdown, msg.BorderColor, msg.Background, msg.Width, msg.MaxHeight, msg.Anchor, msg.Actions, m.width, m.height, ) if m.overlay != nil { cmds = append(cmds, m.overlay.Init()) } case extensionCmdResultMsg: // Async extension slash command completed. Render output/error. if msg.err != nil { m.printSystemMessage(fmt.Sprintf("Command %s error: %v", msg.name, msg.err)) } else if msg.output != "" { m.printSystemMessage(msg.output) } case mcpPromptResultMsg: return m.handleMCPPromptResult(msg, cmds) case externalEditorMsg: // User returned from $EDITOR. Replace input textarea content with // whatever they saved in the temp file. On error (e.g. :cq in vim) // the original input is silently preserved. if msg.err == nil { if ic, ok := m.input.(*InputComponent); ok { ic.textarea.SetValue(msg.text) // Move cursor to the end of the inserted text. ic.textarea.CursorEnd() } m.layoutDirty = true } case editFileMsg: // User returned from $EDITOR after `/edit `. The file was // edited directly on disk — no textarea changes. Report the result. if msg.err != nil { m.printSystemMessage(fmt.Sprintf("Editor exited with error: %v", msg.err)) } else { m.printSystemMessage(fmt.Sprintf("Edited `%s`", msg.path)) } m.layoutDirty = true case extReloadResultMsg: if msg.err != nil { m.printSystemMessage(fmt.Sprintf("Extension reload failed: %v", msg.err)) } else { m.refreshExtensionItems() m.printSystemMessage("Extensions reloaded.") } case beforeSessionSwitchResultMsg: // Async before-session-switch hook completed. Proceed with the // session reset if the hook did not cancel. if msg.cancelled { m.printSystemMessage(msg.reason) m.signalNewSessionResult(fmt.Errorf("session switch cancelled: %s", msg.reason)) } else { cmds = append(cmds, m.performNewSession(msg.initialPrompt)) } case beforeForkResultMsg: // Async before-fork hook completed. Proceed with the fork if the // hook did not cancel. if msg.cancelled { m.printSystemMessage(msg.reason) } else { cmds = append(cmds, m.performFork(msg.targetID, msg.isUser, msg.userText)) } case shareResultMsg: if msg.err != nil { m.printSystemMessage(fmt.Sprintf("Share failed: %v", msg.err)) } else { m.printSystemMessage(fmt.Sprintf("Session shared!\n\n Viewer: %s\n Gist: %s", msg.viewerURL, msg.gistURL)) } return m, nil case app.ExtensionPrintEvent: // Extension output — route through styled renderers when a level is set. switch msg.Level { case "info": m.printSystemMessage(msg.Text) case "error": m.printErrorResponse(app.StepErrorEvent{ Err: fmt.Errorf("%s", msg.Text), }) case "block": m.printExtensionBlock(msg) default: // Plain text from extension — add as system message. m.printSystemMessage(msg.Text) } // ── Clipboard image attached / thumbnail rendered ──────────────────────── // Both messages change the input region's rendered height (the pill and // the async half-block preview), so forward them to the input and mark the // layout dirty — otherwise distributeHeight keeps a stale, too-short input // height and the preview is clipped off the bottom of the screen. case clipboardImageMsg, thumbnailReadyMsg: if m.input != nil { updated, cmd := m.input.Update(msg) m.input, _ = updated.(inputComponentIface) cmds = append(cmds, cmd) } m.layoutDirty = true default: // The /connect key input owns paste and cursor-blink messages while // it is open; the composer must not receive a pasted API key. if m.state == stateProviderConnect && m.providerConnect != nil { updated, cmd := m.providerConnect.Update(msg) m.providerConnect = updated.(*ProviderConnectComponent) cmds = append(cmds, cmd) if _, isPaste := msg.(tea.PasteMsg); isPaste { return m, tea.Batch(cmds...) } } // Pass unrecognised messages to all children. if m.input != nil { updated, cmd := m.input.Update(msg) m.input, _ = updated.(inputComponentIface) cmds = append(cmds, cmd) } if m.stream != nil { updated, cmd := m.stream.Update(msg) m.stream, _ = updated.(streamComponentIface) cmds = append(cmds, cmd) } } return m, tea.Batch(cmds...) } func (m *AppModel) handleImagePreviewReady(msg imagePreviewReadyMsg, cmds []tea.Cmd) (tea.Model, tea.Cmd) { // Each preview becomes its own item, chained after the one before it so // several images attached to one message keep their order. // // Static: the block is decoded pixel data, not a styled text block. // Repainting it would mean re-decoding the image, and only its // background tint comes from the theme. anchor := msg.anchorID placed := false for _, preview := range msg.previews { if preview.cells == "" { continue } item := NewStyledMessageItem(generateMessageID(), "user", "", preview.cells) if preview.image != nil { item = item.WithDirectImage(*preview.image) placed = true } m.insertMessageAfter(anchor, item) anchor = item.ID() } if anchor != msg.anchorID { m.refreshContent() m.layoutDirty = true } if msg.transmit != "" { // The image data cannot travel inside the view text. Placeholder // cells just inserted into the transcript display it as soon as it // lands; a directly-placed image is drawn separately, below. // // It is deliberately never deleted: the message stays in the // scrollback for the rest of the session, and freeing the data // would blank the preview the next time it scrolls into view. cmds = append(cmds, tea.Raw(msg.transmit)) } if placed { // A directly-placed image is drawn by View, which can only work out // where it goes once this frame has been laid out. Nothing else // would arrive to trigger that write, so ask for one more Update // after the coming View. cmds = append(cmds, gfxNudgeCmd()) } return m, tea.Batch(cmds...) } func (m *AppModel) handleMCPPromptResult(msg mcpPromptResultMsg, cmds []tea.Cmd) (tea.Model, tea.Cmd) { // Async MCP prompt expansion completed. Submit the expanded text // as a user message (same behavior as local prompt templates). if msg.err != nil { m.printSystemMessage(fmt.Sprintf("MCP prompt error: %v", msg.err)) } else if msg.text != "" || len(msg.fileParts) > 0 { // Process @file references and submit. processedText := msg.text var fileParts []kit.LLMFilePart if m.cwd != "" { result := fileutil.ProcessFileAttachments(msg.text, m.cwd, m.mcpResourceReader) processedText = result.ProcessedText for _, fp := range result.FileParts { fileParts = append(fileParts, kit.LLMFilePart{ Filename: fp.Filename, Data: fp.Data, MediaType: fp.MediaType, }) } } // Merge file parts from embedded resources (images, audio, blobs) // with any @file/@mcp: file parts extracted from the text. fileParts = append(fileParts, msg.fileParts...) // Build display text with attachment badges (matches the // normal submit path so embedded resources look like pasted // images / attached files). displayText := msg.text if len(msg.fileParts) > 0 { var imageCount, fileCount int for _, fp := range msg.fileParts { if strings.HasPrefix(fp.MediaType, "image/") { imageCount++ } else { fileCount++ } } var badges []string if imageCount > 0 { badges = append(badges, fmt.Sprintf("%d image(s) attached", imageCount)) } if fileCount > 0 { badges = append(badges, fmt.Sprintf("%d file(s) attached", fileCount)) } if len(badges) > 0 { displayText = fmt.Sprintf("%s\n[%s]", msg.text, strings.Join(badges, ", ")) } } if m.appCtrl != nil { var qLen int if len(fileParts) > 0 { qLen = m.appCtrl.RunWithFiles(processedText, fileParts) } else { qLen = m.appCtrl.Run(processedText) } if qLen > 0 { m.queuedMessages = append(m.queuedMessages, displayText) m.layoutDirty = true } else { m.pendingUserPrints = append(m.pendingUserPrints, displayText) m.flushStreamAndPendingUserMessages() } if !m.agentWorking() { m.setAgentState(stateWorking) } } } return m, tea.Batch(cmds...) }