Documentation
¶
Overview ¶
Package script provides a sandboxed Lua scripting surface that lets users bind keys in the TUI to custom actions. It owns a single gopher-lua state, loads .lua files at startup, and dispatches on raw key strings after the built-in keymap misses.
The engine is decoupled from the app/ package through the Host interface so that scripts can manipulate live session state without introducing an import cycle. Host is implemented by a small adapter inside app/ that forwards to the *home model.
Index ¶
- type AttachPane
- type CheckoutIntent
- type Engine
- func (e *Engine) BeginLoad(file string)
- func (e *Engine) CleanupAllCoroutines()
- func (e *Engine) Close()
- func (e *Engine) Dispatch(ctx context.Context, key string, h Host) (matched bool, err error)
- func (e *Engine) DrainLogs() []LogEntry
- func (e *Engine) EndLoad()
- func (e *Engine) HasAction(key string) bool
- func (e *Engine) Load(dir string)
- func (e *Engine) LoadDefaults()
- func (e *Engine) LoadFromString(name, chunk string) error
- func (e *Engine) Registrations() []Registration
- func (e *Engine) Resume(id IntentID, value lua.LValue) (lua.LValue, error)
- func (e *Engine) ResumeWithHost(ctx context.Context, id IntentID, h Host) error
- type FullscreenAttachIntent
- type Host
- type InlineAttachIntent
- type Intent
- type IntentID
- type KillSelectedIntent
- type LogEntry
- type NewInstanceIntent
- type PushSelectedIntent
- type QuickInputIntent
- type QuitIntent
- type Registration
- type ResumeIntent
- type ShowHelpIntent
- type ToggleFileExplorerIntent
- type WorkspacePickerIntent
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AttachPane ¶
type AttachPane int
AttachPane identifies which pane an attach-style intent targets. Used by InlineAttachIntent, FullscreenAttachIntent, and QuickInputIntent so callers don't need to carry separate types per pane variant.
const ( // AttachPaneAgent targets the agent pane (top of the split-pane). AttachPaneAgent AttachPane = iota // AttachPaneTerminal targets the auxiliary terminal pane (bottom). AttachPaneTerminal )
type CheckoutIntent ¶
type CheckoutIntent struct{ Confirm, Help bool }
CheckoutIntent asks the app to check the selected instance's branch out into the root repo. Confirm gates the operation; Help opens the explanatory overlay instead of performing the checkout.
type Engine ¶
Engine owns the single gopher-lua state and the set of registered script actions. All Lua work runs under e.mu because *lua.LState is not goroutine-safe. Scripts themselves are invoked from tea.Cmd goroutines in the app layer — the mutex serializes dispatches so a slow script blocks only subsequent script calls, not the TUI.
func NewEngine ¶
NewEngine constructs a fresh Engine. The LState is opened with the sandbox applied immediately so callers can never accidentally load a script before the sandbox is in place. reserved lists the raw key strings owned by the built-in keymap; scripts trying to bind one are rejected at load time with a warning.
func (*Engine) BeginLoad ¶
BeginLoad brackets a manual load session (tests and the embedded defaults loader). It acquires e.mu and flips the loading flag so cs.bind / cs.register_action accept registrations. Callers must balance every BeginLoad with an EndLoad — the mutex stays held in between. Nested BeginLoad calls panic rather than silently deadlock.
func (*Engine) CleanupAllCoroutines ¶
func (e *Engine) CleanupAllCoroutines()
CleanupAllCoroutines resumes every tracked coroutine with lua.LNil so any deferred work (defers, finalizers, logging) runs before the LState closes. Call this from the app's shutdown hook after Bubble Tea's main loop returns but before Close(). A coroutine that yields again mid-drain is dropped — cleanup is best-effort, not a full dispatch cycle, since the TUI is already gone and there is no host left to service further intents. Ignored errors are logged.
func (*Engine) Close ¶
func (e *Engine) Close()
Close releases the LState. Must be called on shutdown.
func (*Engine) Dispatch ¶
Dispatch looks up key in the registered action map, runs the precondition (if any), and on pass runs the action's run function. Returns (matched, err). matched=false means no script owns this key; matched=true err=nil is a success; matched=true err!=nil is a runtime script error the caller should surface.
ctx carries an optional trace ID (see log.WithTrace) — when present it is emitted on every DebugKV record the handler produces, so the whole dispatch is greppable by one trace ID.
func (*Engine) DrainLogs ¶
DrainLogs returns and clears the buffered log entries emitted via ctx:log() since the last drain. The app layer calls this on a schedule to forward messages to the log package.
func (*Engine) HasAction ¶
HasAction reports whether any script has registered for the given raw key string. The app layer calls this before scheduling a script dispatch Cmd so it can short-circuit unhandled keys without queuing a goroutine.
func (*Engine) Load ¶
Load walks dir and compiles every .lua file it finds. One bad file never fails the whole load — errors go to the app log. Actions registered by prior files are preserved; a partial load is better than no scripts at all. Missing dir is a no-op.
func (*Engine) LoadDefaults ¶
func (e *Engine) LoadDefaults()
LoadDefaults compiles the embedded defaults. A parse or registration error here is a build-time bug — defaults.lua is shipped with the binary — so we panic rather than let broken defaults silently hide behind a log warning.
func (*Engine) LoadFromString ¶
LoadFromString is a test-only entry point that executes the given chunk as a script. Used by tests that want to exercise the API without writing temp files to disk.
func (*Engine) Registrations ¶
func (e *Engine) Registrations() []Registration
Registrations returns a stable, insertion-ordered slice of the currently bound script actions for use by the help panel.
func (*Engine) Resume ¶
Resume wakes the coroutine registered under id with value. If the coroutine completes, the first return value flows back. If it yields again (e.g. because the script chained another cs.await), the slot is re-tracked under the newly-yielded IntentID and Resume returns nil — the host should expect another incoming Enqueue call to have already produced that id.
func (*Engine) ResumeWithHost ¶
ResumeWithHost is the host-facing entry point for continuing a suspended handler coroutine. It sets curHost for the duration of the resume so any deferred cs.actions the coroutine calls next can still reach a live Host. The engine always resumes with lua.LNil — handlers that need a typed value should keep their state in closures rather than in await's return. Errors propagate from the underlying Resume.
curHost swap and the resume itself run under a single critical section so a concurrent Dispatch can't observe the host slot during the window between "curHost = h" and the coroutine actually using it. The resume body runs via resumeLocked, not Resume, to avoid double-locking.
type FullscreenAttachIntent ¶
type FullscreenAttachIntent struct{ Pane AttachPane }
FullscreenAttachIntent asks the app to full-screen attach to the named pane via tea.ExecProcess.
type Host ¶
type Host interface {
// SelectedInstance returns the currently-focused instance in the
// list panel, or nil if the list is empty.
SelectedInstance() *session.Instance
// Instances returns a snapshot slice of every instance currently
// tracked by the list. Callers must not mutate the slice.
Instances() []*session.Instance
// Workspaces returns the loaded workspace registry. May be nil if
// the registry failed to load at startup.
Workspaces() *config.WorkspaceRegistry
// ConfigDir returns the resolved workspace config directory for
// the currently focused workspace.
ConfigDir() string
// RepoPath returns the repo root that new instances should be
// created against (the focused workspace's path, or the current
// directory when no workspace is registered).
RepoPath() string
// DefaultProgram returns the program string (agent command) that
// new instances should launch by default.
DefaultProgram() string
// BranchPrefix returns the branch prefix configured for the
// focused workspace (e.g. "alice/").
BranchPrefix() string
// QueueInstance asks the main goroutine to finalize the given
// instance into the list. The engine calls this from userdata
// methods like ctx:new_instance{}. The actual list mutation is
// deferred to Update — see app.scriptDoneMsg.
QueueInstance(inst *session.Instance)
// Notify posts a transient message to the TUI's error/info bar.
// Called from script userdata through ctx:notify().
Notify(msg string)
// Enqueue hands an Intent to the main goroutine for processing and
// returns the IntentID scripts will match against a later
// Engine.Resume call. Called from cs.actions.* primitives when the
// requested operation cannot be performed synchronously on the
// dispatch goroutine (e.g. anything that opens an overlay).
Enqueue(intent Intent) IntentID
CursorUp()
CursorDown()
ToggleDiff()
WorkspacePrev()
WorkspaceNext()
// Scroll primitives — record UI viewport mutations (applied on the main
// goroutine, like the navigation primitives above). The active-pane
// variants follow the same diff-visible > focused-pane routing rule as
// mouse wheel scrolling.
ScrollLineUp()
ScrollLineDown()
ScrollPageUp()
ScrollPageDown()
ScrollTop()
ScrollBottom()
// Explicit-target terminal scroll primitives — always scroll the
// terminal pane regardless of focus or diff visibility.
ScrollTerminalLineUp()
ScrollTerminalLineDown()
ScrollTerminalPageUp()
ScrollTerminalPageDown()
// Pane-explicit scroll-mode reset — drops the named pane back to
// the live tail. No-op when the pane isn't scrolled. Used to wake
// a scrolled-back pane before opening the quick-input bar.
ResetAgentScroll()
ResetTerminalScroll()
// List navigation primitives — selection jumps.
ListPageUp()
ListPageDown()
ListTop()
ListBottom()
// SendTerminalKeys writes text followed by Enter to the named
// instance's cached terminal-pane tmux session. The terminal pane
// caches sessions per instance title, so this addresses the
// instance-specific session even if a different instance is
// currently displayed. Returns an error if no session is cached
// (e.g. the user has not yet visited that instance's terminal pane,
// or the instance is paused).
SendTerminalKeys(inst *session.Instance, text string) error
}
Host is the facade script userdata uses to touch live TUI state. Every method must be safe to call from a background goroutine — the Engine serializes Lua execution through a mutex but runs the Lua VM itself inside a tea.Cmd goroutine, so any state it touches must be RLock-protected (see session.Instance) or otherwise thread-safe.
type InlineAttachIntent ¶
type InlineAttachIntent struct{ Pane AttachPane }
InlineAttachIntent asks the app to inline-attach to the named pane (keystrokes route to tmux until the user detaches with ctrl+q).
type Intent ¶
type Intent interface {
// contains filtered or unexported methods
}
Intent is the marker interface every script-enqueued UI operation implements. The private intent() method keeps the set closed — only types declared in this file can satisfy it, which lets the app layer's type switch be exhaustive without an explicit default case.
type IntentID ¶
type IntentID uint64
IntentID is the handle a script uses to await an intent's completion. The engine yields it from cs.actions.* primitives; the host later calls Engine.Resume(id, value) once the matching UI flow resolves.
func NewIntentID ¶
func NewIntentID() IntentID
NewIntentID is the exported form for callers outside the package (notably the app layer's scriptHost.Enqueue).
type KillSelectedIntent ¶
type KillSelectedIntent struct{ Confirm bool }
KillSelectedIntent asks the app to kill and clean up the selected instance. Confirm=true gates the destructive action behind an overlay.
type NewInstanceIntent ¶
NewInstanceIntent asks the app to open the new-instance overlay. Prompt=true collects a starter prompt after the title. Title pre-fills the title field when non-empty.
type PushSelectedIntent ¶
type PushSelectedIntent struct{ Confirm bool }
PushSelectedIntent asks the app to push the selected instance's branch to origin. Confirm=true prompts via a confirmation overlay before running the push.
type QuickInputIntent ¶
type QuickInputIntent struct{ Pane AttachPane }
QuickInputIntent opens the quick-input bar targeting the named pane. Text typed there is sent to the backing tmux session on Enter.
type QuitIntent ¶
type QuitIntent struct{}
QuitIntent requests app shutdown. Fulfilled by the app layer's top-level tea.Quit return.
type Registration ¶
Registration describes an action for the help panel. Matches the shape the app layer expects without leaking a scriptAction pointer.
type ResumeIntent ¶
type ResumeIntent struct{}
ResumeIntent asks the app to resume the selected paused instance.
type ToggleFileExplorerIntent ¶ added in v0.1.1
type ToggleFileExplorerIntent struct{}
ToggleFileExplorerIntent opens the file explorer overlay scoped to the currently-selected instance's worktree (or workspace repo, for workspace terminals). The overlay lists files via session/files and invokes $EDITOR on Enter.
type WorkspacePickerIntent ¶
type WorkspacePickerIntent struct{}
WorkspacePickerIntent opens the workspace-picker overlay for switching between registered workspaces.