script

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 20, 2026 License: AGPL-3.0 Imports: 15 Imported by: 0

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

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

type Engine struct {
	L *lua.LState
	// contains filtered or unexported fields
}

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

func NewEngine(reserved map[string]bool) *Engine

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

func (e *Engine) BeginLoad(file string)

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

func (e *Engine) Dispatch(ctx context.Context, key string, h Host) (matched bool, err error)

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

func (e *Engine) DrainLogs() []LogEntry

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) EndLoad

func (e *Engine) EndLoad()

EndLoad terminates a BeginLoad session.

func (*Engine) HasAction

func (e *Engine) HasAction(key string) bool

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

func (e *Engine) Load(dir string)

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

func (e *Engine) LoadFromString(name, chunk string) error

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

func (e *Engine) Resume(id IntentID, value lua.LValue) (lua.LValue, error)

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

func (e *Engine) ResumeWithHost(ctx context.Context, id IntentID, h Host) error

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 — mutate UI viewport state synchronously. 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()

	// List navigation primitives — selection jumps.
	ListPageUp()
	ListPageDown()
	ListTop()
	ListBottom()
}

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 LogEntry

type LogEntry struct {
	Level   string
	Message string
}

LogEntry is a single script-emitted log record.

type NewInstanceIntent

type NewInstanceIntent struct {
	Prompt bool
	Title  string
}

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

type Registration struct {
	Key  string
	Help string
}

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 ShowHelpIntent

type ShowHelpIntent struct{}

ShowHelpIntent opens the help overlay.

type WorkspacePickerIntent

type WorkspacePickerIntent struct{}

WorkspacePickerIntent opens the workspace-picker overlay for switching between registered workspaces.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL