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 snapshots reads from, and defers writes to, the *home model.
Index ¶
- type AttachPane
- 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
- func (e *Engine) Shutdown(timeout time.Duration)
- type FullscreenAttachIntent
- type Host
- type InlineAttachIntent
- type Intent
- type IntentID
- type KillSelectedIntent
- type LogEntry
- type MergeSessionsIntent
- type NewFromIssueIntent
- type NewInstanceIntent
- type OpenReviewIntent
- type PushSelectedIntent
- type QuickInputIntent
- type QuitIntent
- type Registration
- type RestartWithOptionsIntent
- type ResumeIntent
- type SettingsIntent
- type ShowHelpIntent
- type StashIntent
- 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 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. The Update-goroutine queries (HasAction, Registrations) never take mu: they read bindings, which bind/unbind republish.
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. Shutdown runs it before closing the engine. 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. The app shuts down through Shutdown, which bounds the wait for a running handler; Close waits indefinitely.
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. After Close it returns errEngineClosed.
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 bounded test capture of recent script-emitted log entries (see the logs field doc). It is NOT how these entries reach loom.log or the TUI — logScript writes straight to the structured logger for that, synchronously, every time. Nothing in production calls DrainLogs; it exists so tests can assert what a script logged without standing up a real logger sink. Do not call it from the app's Update loop: it takes e.mu, which a running handler can hold for the length of its dispatch, and calling it from Update would block the UI on that handler exactly the way the engine's other Update-goroutine queries (HasAction, Registrations) are designed to avoid.
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. Reads the published snapshot, so it never waits for a running handler.
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. It copies the published snapshot, so it never waits for a running handler.
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, and rebinds the handler's ctx to h so ctx reads after the yield see h's state and ctx side effects (notify, new_instance) reach h rather than the already-drained dispatch 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.
func (*Engine) Shutdown ¶ added in v0.13.0
Shutdown releases the engine at process exit and returns within timeout even if a handler is still running. It first tries the normal path: drain parked coroutines (so their post-yield work runs) and Close. If that hasn't finished by half the budget, because a handler holds e.mu or a drained coroutine is itself stuck, it cancels the Lua context, which makes Lua raise at its next instruction, and waits out the rest. A handler blocked inside a Go call can't be interrupted: then Shutdown logs engine_busy_at_shutdown, naming the stuck handler's key and file (inFlight), and returns without cleaning up, and process exit reclaims everything.
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 instance focused in the list panel
// when the dispatch or resume began, or nil if the list was empty.
SelectedInstance() *session.Instance
// Instances returns every instance the list tracked when the
// dispatch or resume began. Callers must not mutate the slice.
Instances() []*session.Instance
// 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()
// Fleet primitives — rail/terminal-pane visibility, split resize,
// and attention jumps. Deferred model mutations like the scroll
// primitives above.
NextWaiting()
PrevWaiting()
ToggleRail()
ToggleTerminalPane()
// ToggleOverview flips the top-level presentation between focus
// (rail + panes) and the fleet-overview card grid, persisting the
// chosen mode so it survives restarts.
ToggleOverview()
ResizeSplitUp()
ResizeSplitDown()
// 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, concurrently with the app's Update/View. The app's host therefore answers the query methods from a snapshot taken on the Update goroutine when the dispatch or resume began (a handler never sees later changes, including its own deferred ones) and records mutations for Update to apply. Returned instances are shared: session.Instance locks internally.
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 MergeSessionsIntent ¶ added in v0.3.0
type MergeSessionsIntent struct{}
MergeSessionsIntent asks the app to open the merge-session picker for the currently-selected instance. The picker itself (and the merge it performs on commit) run entirely as plain Go state-handler code once opened — this intent's only job is getting the picker on screen.
type NewFromIssueIntent ¶ added in v0.13.0
type NewFromIssueIntent struct{}
NewFromIssueIntent asks the app to open the GitHub issue picker; the chosen issue seeds a new session's title and prompt.
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 OpenReviewIntent ¶ added in v0.13.0
type OpenReviewIntent struct{}
OpenReviewIntent asks the app to open the workbench on the review tab for the selected instance (code review over the worktree diff).
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 RestartWithOptionsIntent ¶ added in v0.6.0
type RestartWithOptionsIntent struct{}
RestartWithOptionsIntent asks the app to open the Session Launch Options modal for the selected Paused instance, seeded from its current (reverse-parsed) launch options, so the user can change them before resuming.
type ResumeIntent ¶
type ResumeIntent struct{}
ResumeIntent asks the app to resume the selected paused instance.
type SettingsIntent ¶ added in v0.3.0
type SettingsIntent struct{}
SettingsIntent opens the settings overlay for editing config.json fields.
type StashIntent ¶ added in v0.6.0
type StashIntent struct{ Confirm, Help bool }
StashIntent asks the app to stash the selected instance's uncommitted changes and pause it, checking its branch out into the root repo. Confirm gates the operation; Help opens the explanatory overlay instead of performing the stash.
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.