tui

package
v1.15.0 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2026 License: MIT Imports: 49 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package tui is the Go TUI's shell: the Bubble Tea root model, the screen geometry, view switching, the task list and its selection, and the right panel that shows task and project details.

It is a REBUILD of lib/tui/app.rb on Bubble Tea, not a transliteration. The Ruby terminal event loop, its raw-mode key decoder, its paint-dirty bookkeeping and its winsize polling are all things Bubble Tea already owns, so none of them are ported. What IS ported is everything Bubble Tea has no opinion about: which rows a view emits, how selection survives a refresh, what the panel says, and how the screen is divided.

Everything in this file's neighbourhood is deliberately pure. Row building, geometry, panel scrolling and detail content are functions from values to values, so they are tested by calling them rather than by scraping a terminal.

Index

Constants

View Source
const (
	DelegatedGlyph = "→"
	ClaimedGlyph   = "⇒"
	// DelegationAssigneeWidth is the cells an assignee may occupy before it is
	// cut back to `local@…`. Wide enough for pat@example.com, narrow enough to
	// leave the title readable in a split pane.
	DelegationAssigneeWidth = 16
)

The delegation row markers. A single arrow means "handed off and idle" — a person we are waiting on, or agent-ready work nobody has picked up. A doubled arrow means a worker is actively holding the task, and it is the one delegation state where acting on the row would collide with someone else's work, so it is deliberately the loudest.

The two are distinguishable WITHOUT color: different glyphs, and the accent slot resolves to bold in every monochrome theme while muted resolves to dim.

View Source
const (
	// FixedRows is the header plus the two blank rows that separate it and the
	// footer from the body. The frame itself is undrawn — see render.go.
	FixedRows = 3

	PanelRatio          = 0.40
	WidePanelRatio      = 0.58
	MinPanelWidth       = 28
	MinListWidth        = 8
	EditMinContentWidth = 32
	InlineContentWidth  = 48
	EditPanelChromeRows = 2 // RightPanel title and divider
	EditMinVisibleRows  = 1 // compact focused-field fallback
)

The panel width ladder. Names and numbers are Ruby's.

View Source
const (
	MinWidth  = 8
	MinHeight = 6
	// TickInterval is the file-watch poll. Bubble Tea drives it as a command
	// rather than as an IO.select timeout; the interval is Ruby's.
	TickInterval = 250 * time.Millisecond
	// FlashDuration is how long a status message stays up. Ruby's three
	// seconds, unchanged: it is long enough to read one line and short enough
	// that a stale message never gets mistaken for a live one.
	FlashDuration = 3 * time.Second
)

Minimum frame that can retain borders, margins, and content.

View Source
const (
	PanelDetail            = "detail"
	PanelProjectDetail     = "project_detail"
	PanelSuspendedTaskEdit = "suspended_task_edit"
)

Panel kinds. A panel's kind decides which refresh path keeps it current and which keys it answers.

View Source
const (
	MarkExpanded  = "▾ "
	MarkCollapsed = "▸ "
	MarkLeaf      = "  "
)

The collapse markers, each exactly two terminal cells. Every tree-mode task row carries one so titles align regardless of whether a node has children.

View Source
const (
	// CursorField is the selection gutter: `❯ ` on the selected row, two spaces
	// on every other. Two cells, matching the collapse marker, so a selected
	// collapsed row reads `❯ ▸ title` rather than as a doubled marker.
	CursorField = 2
	// BandField is the urgency band: a `▌` painted in the row's due slot, plus
	// its separation. It is the leftmost thing in a row's own text, so a block
	// of overdue work reads as a red edge down the side of the list before any
	// word on it has been read.
	BandField = 2
	// MarkerField is the collapse marker: `▾ `, `▸ ` or the two blanks a leaf
	// spends to hold the column (see MarkLeaf). It sits between the band and the
	// body, and EVERY row in a list that has one pays it, leaf or not — that is
	// what keeps one left edge under a block of proposals and a block of nested
	// inbox rows alike.
	MarkerField = 2
	// PriorityField is the priority letter plus its separation: `A  ` or three
	// spaces. It sits INSIDE the body, immediately after the state glyph, where
	// the design puts it — a letter next to the title it ranks, not a lonely
	// column at the far left.
	PriorityField = 3
	// MetaColumn is the shared right-hand column. Ten cells is the widest thing
	// any view puts there: `tue 08-11`, `1d ago`, `12/34`.
	MetaColumn = 10
	// ContextColumn is the second right-hand column, holding the row's `@`
	// contexts right-aligned against the meta column's left edge. Contexts used
	// to trail the title inline, which made every title end at a different
	// place and turned the contexts into noise attached to the words; as a
	// column they become a thing you can scan down. Thirteen cells fits
	// `@computer` and a second short tag.
	ContextColumn = 13
	// MinTitleWidth is how much title has to survive before the meta column is
	// worth having at all. Below it the layout degrades to a plain left-aligned
	// row with the meta carried inline.
	MinTitleWidth = 16
)

The shared list vocabulary — the part of the design system that is not any one view's business.

Three rules, and every view obeys all three:

  • EVERY block opens with a section rule: an uppercase label, a `─` run to the right edge, and a right-aligned count or status word. A view with no natural grouping still gets one rule, because the rule is what says where a block begins and how much is in it.
  • EVERY list on the screen shares ONE right meta column. Dates, counts and status words line up down a single edge across sections and across views, so switching tabs does not move the column the eye is already reading.
  • EVERY row has the same head: two cells of cursor, then two of urgency band. A title starts at the same column whether or not a row is selected and whether or not it is prioritized.

A view that cannot fill the meta column leaves it empty. It does not reclaim the space, because a column that moves when a value is missing is not a column.

View Source
const (
	DotClosed   = "●"
	DotProgress = "■"
	DotOpen     = "○"
)

The record-state glyphs. A state word says which of eight states a task is in; the glyph says the only thing a scan needs — done, being done, not started — and it says it in one cell at the head of the row.

View Source
const (
	ViewAgenda    = "agenda"
	ViewNext      = "next"
	ViewQuadrants = "quadrants"
	ViewProjects  = "projects"
	ViewOutline   = "outline"
	ViewInbox     = "inbox"
)

The six tabs, in order. The number is part of the label because the number is also the key that jumps to the tab.

View Source
const Band = "▌"

Band is the urgency band glyph — see BandField.

View Source
const Cursor = "❯ "

Cursor is the selection glyph, gold in the comp and the same two cells as term/frame's own. It is deliberately distinct from the collapsed-row marker.

View Source
const MoreGlyph = "▾"

MoreGlyph marks a row that stands for rows you cannot see.

View Source
const SessionVersion = 1

SessionVersion is the on-disk schema of the saved TUI state. A file naming any other version is ignored wholesale, exactly as Ruby ignores it.

View Source
const TabGap = "   "

TabGap is the space between tab names. Three cells, not one: with the jump numbers gone the strip is six bare words, and one space between them reads as a sentence rather than as a set of tabs.

View Source
const UnfiledIntake = "Inbox"

UnfiledIntake is the one bucket every intake row with no project of its own lands in: a task sitting directly in the file's Inbox section, and a task sitting under no section at all, are the same thing to a reader triaging them — unfiled. It is a display key as well as a bucket key, so it is spelled the way the file spells that section rather than as a marker word.

Variables

View Source
var PanelModes = []string{"compact", "standard", "wide", "focus"}

PanelModes is the promotion ladder, narrowest first.

View Source
var Tabs = []Tab{
	{"agenda", "ag", "ag", ViewAgenda},
	{"next", "nx", "nx", ViewNext},
	{"quadrants", "quad", "q", ViewQuadrants},
	{"projects", "proj", "pr", ViewProjects},
	{"outline", "out", "out", ViewOutline},
	{"inbox", "in", "in", ViewInbox},
}

Tabs is the canonical tab order. Views, the jump keys and the session's saved view all read this one list.

Functions

func AgentAvailability added in v1.1.0

func AgentAvailability(env determinism.Env, conf llm.Config, dataDir string) func(agent.Entry) bool

AgentAvailability is the context-free submit-time provider probe.

func AgentFactory added in v1.1.0

func AgentFactory(paths config.Paths, env determinism.Env, conf llm.Config,
	dataDir, cliPath string) func(agent.Entry) (agent.Adapter, error)

AgentFactory creates a provider adapter with fresh Tasks system context when a queued request starts.

func ApplyModalBackdrop added in v1.14.0

func ApplyModalBackdrop(styler Styler, leftOfBox, rightOfBox string) (string, string)

ApplyModalBackdrop wraps the frame cells OUTSIDE a modal box on the rows the box spans in the backdrop slot, returning both margins for the caller to splice around the box line:

left + boxLine + right

The seam takes already-sliced strings because the frame carries escape sequences and every cut here must go through the cell-aware slicer — the same rule overlay.go's composite follows. mono deliberately covers this slot with "dim": attribute-only dimming is consistent with mono styling everything else, and keeps the float readable under NO_COLOR. A user or host who sets the slot to "none" gets the old flat look back.

func ChromeHorizontal added in v1.14.0

func ChromeHorizontal(styler Styler, variant BoxVariant, n int) string

ChromeHorizontal runs horizontal border of width n, painted for variant.

func ClampScroll added in v1.14.0

func ClampScroll(offset, visible, total int) int

ClampScroll bounds a scroll offset to what content actually allows.

func EmbeddedSessionPath added in v1.1.0

func EmbeddedSessionPath(env determinism.Env, namespace string) string

EmbeddedSessionPath keeps a host's presentation state separate from the standalone TUI. The public adapter validates namespace before calling it.

func ExportMarkdown

func ExportMarkdown(item store.Item, notes []string) string

ExportMarkdown is the whole task as pasteable markdown. `notes` is the item's prose lines, already filtered.

func ExportReference

func ExportReference(item store.Item) string

ExportReference is the stable id to paste into the agent prompt.

It is the ID and not the title on purpose: an exact id stays unambiguous across duplicate titles and across a later retitle, which is exactly what a reference in a conversation has to survive.

func FormatTemporal

func FormatTemporal(value any) string

FormatTemporal is ParseTemporal's inverse: the canonical spelling the editor buffer holds. Round-tripping matters — the buffer is what the user edits.

func KeySequence

func KeySequence(message tea.KeyPressMsg) string

KeySequence turns a decoded Bubble Tea v2 key press into the raw byte sequence the shortcut registry and the text editor are both keyed by.

It is exported because the differential harness drives the model with the SAME sequences it feeds Ruby's key handler, which is the only way the two interaction traces are comparable. An external Bubble Tea v2 host can pass tea.KeyPressMsg values straight into Update without translation.

func MinimumEditTerminalHeight

func MinimumEditTerminalHeight(footerRows int) int

MinimumEditTerminalHeight is the shortest terminal that can host the editor with the given number of footer rows. Every footer or help row consumes another terminal row before the panel title, divider, and focused fallback.

func MinimumEditTerminalWidth

func MinimumEditTerminalWidth() int

MinimumEditTerminalWidth is the narrowest terminal that can host the editor.

func NormalizeContextFilters

func NormalizeContextFilters(values []string) []string

NormalizeContextFilters is UiState.normalize_context_filters: keep the non-empty strings, give each a leading "@", drop anything shorter than two characters, deduplicate, and sort. Sorting is what makes the saved value stable across runs, so an unchanged filter set does not rewrite the file.

func OffsetAtRow added in v1.14.0

func OffsetAtRow(totalItems, visibleItems, trackHeight, row int) int

OffsetAtRow maps a track row to the smallest scroll offset whose thumb top renders on or below that row — the jump-to-spot contract a future track-press gesture will use. Clamped to [0, totalItems-visibleItems]; monotonic in row. Adapted from sidecar's internal/scroll/thumb.go.

func PaintBorderSlot added in v1.14.0

func PaintBorderSlot(styler Styler, slot, piece string) string

PaintBorderSlot paints one border piece in a NAMED slot — the per-field box treatment (field_border / field_border_focused) and any other border that is chrome but not the modal frame. An empty slot passes the piece through untouched, the same passthrough a neutral BoxVariant gets.

func PaintChrome added in v1.14.0

func PaintChrome(styler Styler, variant BoxVariant, piece string) string

PaintChrome renders one border piece in its variant's slot. A neutral (or unknown) variant returns the piece untouched, which is the same string the un-chromed renderers emit today. Glyphs come from border.Round so the corners match every other rounded surface in the TUI.

func PaintKeyChips added in v1.14.0

func PaintKeyChips(styler Styler, chips []KeyChip) string

PaintKeyChips renders chips left to right. An empty list paints an empty line — callers decide whether to spend the row at all.

func PaintModalButton added in v1.14.0

func PaintModalButton(styler Styler, b ModalButton) string

PaintModalButton renders one button in its variant's slot.

func PaintScrollbar added in v1.14.0

func PaintScrollbar(styler Styler, trackHeight int, thumb ScrollThumb) string

PaintScrollbar paints a whole column at once, for callers that build a single string per row anyway. An empty result means "no scrollbar".

func PaintStatusLine added in v1.14.0

func PaintStatusLine(styler Styler, level StatusLevel, message string) string

PaintStatusLine renders one status message, or "" when there is none.

func ParseTemporal

func ParseTemporal(text string, today temporal.Date, context temporal.Context) (any, error)

ParseTemporal reads the editor's date grammar: a date expression with an optional wall time and an optional trailing zone / floating / fold token.

func RowForOffset added in v1.14.0

func RowForOffset(totalItems, visibleItems, trackHeight, offset int) int

RowForOffset maps a scroll offset to the track row where the thumb top renders, clamped to [0, trackHeight-1]. Adapted from sidecar's internal/scroll/thumb.go.

func SaveEmbeddedSession added in v1.1.0

func SaveEmbeddedSession(state SessionState, env determinism.Env, namespace string) error

SaveEmbeddedSession writes a host-specific embedded session.

func SaveSession

func SaveSession(state SessionState, env determinism.Env) error

SaveSession overwrites the saved state. Best-effort: a read-only state directory must not crash TUI exit, so the error is reported and ignorable.

func ScrollbarCell added in v1.14.0

func ScrollbarCell(styler Styler, row int, thumb ScrollThumb) string

ScrollbarCell paints one row of a scrollbar column. Rows outside the thumb paint as track; when thumb.Has is false there is nothing to scroll and the caller should draw no column at all.

func SessionPath

func SessionPath(env determinism.Env) string

SessionPath is $XDG_STATE_HOME/tasks/tui.json, resolved against the caller's environment rather than the process environment — the same threading Wave 0 had to fix in config.parseFile, for the same reason: a harness that pins HOME must be obeyed.

func ViewKeys

func ViewKeys() []string

ViewKeys is the tab keys alone.

func ZoneIdentifiers

func ZoneIdentifiers() []string

ZoneIdentifiers is every IANA zone this host can load, Area/Location or UTC.

Go has no equivalent of TZInfo.all_identifiers, so the zoneinfo tree is walked. A host with no tree at all still gets the handful of zones the runtime always resolves, so the search is never empty.

Types

type ActionPalette

type ActionPalette struct {
	// contains filtered or unexported fields
}

ActionPalette is the searchable projection of the actions available right now. It owns query and selection state only; the model executes the chosen registry entry.

func NewActionPalette

func NewActionPalette(styler Styler, entries []shortcuts.Entry, returnMode ReturnMode, targetID string) *ActionPalette

NewActionPalette builds one over a set of available entries.

func (*ActionPalette) Fail

func (a *ActionPalette) Fail(message string)

Fail attaches an error, so a failed action is reported in the palette the user chose it from rather than as a bare flash behind a closed overlay.

func (*ActionPalette) HandleKey

func (a *ActionPalette) HandleKey(key string) PaletteOutcome

HandleKey routes one key and resolves an acceptance back to a registry entry.

func (*ActionPalette) Hit

func (a *ActionPalette) Hit(rowOffset int) PaletteOutcome

Hit routes one click.

func (*ActionPalette) Move

func (a *ActionPalette) Move(delta int) PaletteOutcome

Move steps the cursor.

func (*ActionPalette) Paste

func (a *ActionPalette) Paste(text string) PaletteOutcome

Paste inserts pasted text into the query.

func (*ActionPalette) Picker

func (a *ActionPalette) Picker() *ChoicePicker

Picker exposes the underlying picker for rendering and hit testing.

func (*ActionPalette) ReturnMode

func (a *ActionPalette) ReturnMode() ReturnMode

ReturnMode and TargetID are what the model needs to close it correctly.

func (*ActionPalette) TargetID

func (a *ActionPalette) TargetID() string

type AgentAdapter

type AgentAdapter struct {
	// contains filtered or unexported fields
}

AgentAdapter bridges one *llm.Agent to the queue's Adapter interface.

The two shapes differ in exactly one way that matters: llm.Agent is a long-running process with a Done channel, and the queue is a POLLED thing driven from the TUI's tick. Pump therefore must never block — a blocking read here would freeze the whole interface for as long as the model was thinking. So Pump asks the Done channel whether the process has finished and returns immediately either way; the transcript is read from the agent's own buffer, which its drain goroutine keeps filled.

It lives in internal/tui rather than in cmd/tasks-tui so it can be tested without a terminal, and it is deliberately thin: every decision about the process — argv, streaming, cancellation grace, signal handling — stays in internal/llm, which the CLI shares.

func NewAgentAdapter

func NewAgentAdapter(built *llm.Agent) *AgentAdapter

NewAgentAdapter wraps a built agent.

func (*AgentAdapter) Available

func (a *AgentAdapter) Available() bool

Available re-checks the provider at start time.

func (*AgentAdapter) Cancel

func (a *AgentAdapter) Cancel() error

Cancel signals the process group and waits out the short grace period the llm layer owns.

func (*AgentAdapter) ExitStatus

func (a *AgentAdapter) ExitStatus() (int, bool)

ExitStatus is the process exit code once it is known.

The second return is the whole contract: the queue turns `false` into an ABSENT exit status on the request snapshot, and llm.Agent reports -1 for both "has not exited" and "died on a signal". Reporting (-1, true) would put an exit code no process ever returns onto a cancelled request — which is exactly the path the TUI reaches every time a user presses escape on a running agent.

func (*AgentAdapter) Output

func (a *AgentAdapter) Output() string

Output is the transcript captured so far.

func (*AgentAdapter) ProcessStatus

func (a *AgentAdapter) ProcessStatus() agent.ProcessStatus

ProcessStatus is how the process ended, including the signal a cancellation delivered — which is what tells "the user cancelled it" apart from "it crashed".

func (*AgentAdapter) Pump

func (a *AgentAdapter) Pump() (bool, error)

Pump reports whether the process has finished, without blocking.

func (*AgentAdapter) Start

func (a *AgentAdapter) Start(prompt, model string) error

Start launches the process with streaming ON, so the activity modal and the footer can show the transcript as it arrives rather than only at the end.

func (*AgentAdapter) Success

func (a *AgentAdapter) Success() bool

Success reports a clean exit that was not cancelled.

type AgentEntry

type AgentEntry = agent.SimpleEntry

AgentEntry is one provider/model the prompt can be submitted to. It is the queue's Entry with a display label the header shows.

func BuildAgentQueue added in v1.1.0

func BuildAgentQueue(paths config.Paths, env determinism.Env) ([]AgentEntry, *agent.Queue, error)

BuildAgentQueue constructs the Tasks-owned provider/model registry and queue.

type BoxVariant added in v1.14.0

type BoxVariant int

BoxVariant selects a modal's border look.

const (
	BoxNeutral BoxVariant = iota
	// BoxAccent frames an ordinary dialog.
	BoxAccent
	// BoxWarning frames an armed destructive confirmation.
	BoxWarning
	// BoxDanger frames a fully destructive surface.
	BoxDanger
)

func (BoxVariant) BorderSlot added in v1.14.0

func (v BoxVariant) BorderSlot() string

BorderSlot maps a variant to its theme slot. Neutral returns "" — no paint — so existing callers keep their current look until they opt in.

type BuildRequest

type BuildRequest struct {
	View         string
	Styler       Styler
	Queries      *taskquery.Queries
	Items        []store.Item // already narrowed by the active `/` and `@` filters
	Tree         []*taskquery.Node
	UseTree      bool
	Collapsed    map[string]bool
	ShowDeferred bool
	// ShowRejected reveals recently declined proposals inside APPROVALS. It is
	// off by default: intake is a queue of undecided work, and a decision already
	// made is not part of it until the reviewer asks to see it.
	ShowRejected   bool
	UrgentDays     int
	ContextFilters []string
	// TextFilter is the active `/` search, lowercased by the caller's own rule
	// (plain title substring). Items already arrives narrowed by it; builders
	// that fetch rows from Queries directly (revealed rejects) must apply it
	// themselves so a filtered view never shows rows the filter hides.
	TextFilter   string
	Projects     []taskquery.ProjectView
	IntakeCounts IntakeCounts

	// Width is the list's content width in cells, excluding the renderer's
	// cursor gutter. Only the agenda uses it, and only to align its date
	// column; zero means "not measured" and every builder still produces
	// correct rows. See agenda.go.
	Width int
}

BuildRequest is everything the row builders need. It is a value, so building rows is a pure function of a read model plus the UI's own choices — which is what makes every row test a table test rather than a screen scrape.

type ButtonVariant added in v1.14.0

type ButtonVariant int

ButtonVariant selects a button's look.

const (
	// ButtonPrimary is the one affirmative action: submit. Filled.
	ButtonPrimary ButtonVariant = iota
	// ButtonDanger outlines a destructive affordance: release, undelegate.
	ButtonDanger
	// ButtonDangerArmed is the destructive affordance after its first press:
	// filled, loud, asking for the second press that acts.
	ButtonDangerArmed
	// ButtonMuted is cancel and other exits. Quiet on purpose.
	ButtonMuted
)

type ChoicePicker

type ChoicePicker struct {
	// contains filtered or unexported fields
}

ChoicePicker is the stable, searchable overlay both palettes are built from.

"Stable" is the operative word and it is why this is one type rather than two ad-hoc lists: the box width comes from the FULL option set, the viewport follows the cursor rather than the match count, and the layout the mouse hit test reads is the layout the last paint produced. A palette whose rows moved between the paint and the click would run the wrong action.

func NewChoicePicker

func NewChoicePicker(options ChoicePickerOptions) *ChoicePicker

NewChoicePicker builds one.

func (*ChoicePicker) AcceptVisible added in v1.7.0

func (p *ChoicePicker) AcceptVisible(index int) (PickerResult, bool)

AcceptVisible accepts a 1-based row from the most recently rendered popup. Before a render, or outside its actual result slots, it declines so callers can preserve the key's ordinary input behavior.

func (*ChoicePicker) Current

func (p *ChoicePicker) Current() *PickerOption

Current is the option under the cursor, or nil.

func (*ChoicePicker) CursorIndex

func (p *ChoicePicker) CursorIndex() int

func (*ChoicePicker) Error

func (p *ChoicePicker) Error() string

func (*ChoicePicker) Fail

func (p *ChoicePicker) Fail(message string)

Fail attaches an error to the picker without closing it, so a failed action is reported where the user chose it.

func (*ChoicePicker) HandleKey

func (p *ChoicePicker) HandleKey(key string) PickerResult

HandleKey routes one raw key.

func (*ChoicePicker) Hit

func (p *ChoicePicker) Hit(rowOffset int) PickerResult

Hit maps a popup-local row (0 = the top border) to a picker action, returning the SAME shapes HandleKey does so a click and a keypress cannot diverge.

func (*ChoicePicker) Input

func (p *ChoicePicker) Input() string

func (*ChoicePicker) InputCursor

func (p *ChoicePicker) InputCursor() int

func (*ChoicePicker) Move

func (p *ChoicePicker) Move(delta int) PickerResult

Move steps the cursor and keeps it visible. Same step as ↑↓, for the wheel and for programmatic motion.

func (*ChoicePicker) Options

func (p *ChoicePicker) Options() []PickerOption

func (*ChoicePicker) Paste

func (p *ChoicePicker) Paste(text string) PickerResult

Paste inserts pasted text into the query.

func (*ChoicePicker) Popup

func (p *ChoicePicker) Popup(styler Styler, maxWidth, maxHeight int, inlineInput func(string, int) string) []string

Popup renders the overlay at the given budget and records the layout the hit test reads.

The three tiers are deliberate. A palette that simply refused to render in a short terminal would take a capability away from a user whose window happened to be small; each tier keeps the one thing that tier can still show — the current option, the query, and the hint.

func (*ChoicePicker) RefreshOptions

func (p *ChoicePicker) RefreshOptions(options []PickerOption, selection []string)

RefreshOptions swaps the option set while keeping the query, the staged selection and — where it still exists — the cursor's option.

func (*ChoicePicker) Results

func (p *ChoicePicker) Results() []PickerOption

Results is the option set narrowed and RANKED by the live query.

The ranking is what makes typing three letters land on the thing you meant: exact match, then prefix, then a word-boundary prefix, then a substring — ties broken by declaration order, so the answer is the same on every run.

func (*ChoicePicker) Selected

func (p *ChoicePicker) Selected(id string) bool

Selected reports whether an id is in the staged set.

func (*ChoicePicker) SelectionChanged

func (p *ChoicePicker) SelectionChanged() bool

SelectionChanged reports whether the staged set differs from what the picker opened with. The context palette reads it to decide whether Return means "apply what I toggled" or "apply just the thing under the cursor".

func (*ChoicePicker) Staged

func (p *ChoicePicker) Staged() []string

Staged is the selection as it stands, sorted for a stable answer.

func (*ChoicePicker) Title

func (p *ChoicePicker) Title() string

Title, Input, CursorIndex, ViewportStart, Staged and Error are the accessors.

func (*ChoicePicker) ViewportStart

func (p *ChoicePicker) ViewportStart() int

type ChoicePickerOptions

type ChoicePickerOptions struct {
	Title            string
	Options          []PickerOption
	Selection        []string
	Mode             SelectionMode
	AcceptLabel      string
	EmptyLabel       string
	MaxVisible       int
	PreferredID      string
	ToggleCommand    func(option PickerOption, staged []string) ([]string, bool)
	SearchNormalizer func(string) string
	SelectedStyle    string
}

ChoicePickerOptions builds a picker.

type ContextOutcome

type ContextOutcome struct {
	Kind PickerResultKind
	// Contexts is the filter set to apply when Kind is PickerAccepted.
	Contexts []string
	Apply    bool
}

ContextOutcome is what a context-palette key did.

type ContextPalette

type ContextPalette struct {
	// contains filtered or unexported fields
}

ContextPalette is the multiple-choice adapter over the TUI's global @context filters. The picker owns interaction; the model owns applying the result.

func NewContextPalette

func NewContextPalette(contexts, current []string) *ContextPalette

NewContextPalette builds one over the contexts the store currently holds.

func (*ContextPalette) CurrentFilters

func (c *ContextPalette) CurrentFilters() []string

CurrentFilters is the filter set the palette opened with.

func (*ContextPalette) HandleKey

func (c *ContextPalette) HandleKey(key string) ContextOutcome

HandleKey routes one key.

func (*ContextPalette) Hit

func (c *ContextPalette) Hit(rowOffset int) ContextOutcome

Hit routes one click.

func (*ContextPalette) Move

func (c *ContextPalette) Move(delta int) ContextOutcome

Move steps the cursor.

func (*ContextPalette) Paste

func (c *ContextPalette) Paste(text string) ContextOutcome

Paste inserts pasted text into the query.

func (*ContextPalette) Picker

func (c *ContextPalette) Picker() *ChoicePicker

Picker exposes the underlying picker.

func (*ContextPalette) RefreshOptions

func (c *ContextPalette) RefreshOptions(contexts, current []string)

RefreshOptions adopts a fresh context list without losing what is staged.

type DetailContent

type DetailContent struct {
	Title string
	Lines []string
}

DetailContent is one panel's worth of content.

func BuildProjectDetails

func BuildProjectDetails(styler Styler, queries *taskquery.Queries, project taskquery.ProjectView,
	tasks []store.Item, width int) DetailContent

BuildProjectDetails is the ProjectView counterpart — the port of lib/tui/project_details.rb. `tasks` is the resolved open task list; the builder never reaches back into a store or an application.

func BuildTaskDetails

func BuildTaskDetails(styler Styler, queries *taskquery.Queries, item store.Item,
	width int, projectName string) DetailContent

BuildTaskDetails is the pure task-detail content builder — the port of lib/tui/task_details.rb. Its output is hosted by the right panel today and could be hosted by any other surface tomorrow, because it depends on no modal, no store, and no panel state.

type EditSnapshot

type EditSnapshot struct {
	ID       string
	Title    string
	Priority string
	Deferred bool
	// Scheduled and Deadline are nil when the task has no such date. A nil is
	// meaningfully different from a zero date: it means "clear this".
	Scheduled  *temporal.Value
	Deadline   *temporal.Value
	Recurrence string
	Lead       string
	Contexts   []string
	Tags       []string
	Body       string
	State      string
	Closed     string
	// SubtreeIDs is the task and its descendants, in document order, so a
	// completion confirmation can say how many tasks ride along.
	SubtreeIDs []string
	// contains filtered or unexported fields
}

EditSnapshot is one coherent read of a task PLUS the per-field baselines the store will compare a patch against.

STRUCTURAL NOTE, and the one place this packet had to build rather than port. Ruby has `Tasks::EditSnapshot`, produced by `application.edit_snapshot(id)`, which carries every field, its baseline and the task's revision. The Go application facade publishes the values and field expectations through one held ReadModel. This assembles the editor shape without taking a second store read, so every buffer and every expectation describes the same bytes.

The important property is preserved: every baseline in a snapshot comes from one moment, so a patch's conflict check compares against the value the user was actually looking at.

func NewEditSnapshot

func NewEditSnapshot(app *application.Application, read *application.ReadModel, id string) (*EditSnapshot, bool)

NewEditSnapshot builds a snapshot for one task from a live read model, or reports that the task is not there.

func (*EditSnapshot) ExpectedFor

func (s *EditSnapshot) ExpectedFor(field string) string

ExpectedFor is the baseline a patch on one field must match.

func (*EditSnapshot) OpenDescendantIDs

func (s *EditSnapshot) OpenDescendantIDs(read *application.ReadModel) []string

OpenDescendantIDs is every open task strictly beneath this one — what a cascade completion would also close.

func (*EditSnapshot) Value

func (s *EditSnapshot) Value(field string) any

Value is the snapshot's value for one editor field, in the shape the matching form field holds.

func (*EditSnapshot) Values

func (s *EditSnapshot) Values() map[string]any

Values is every field's value.

type EditorConfirmationPrompt

type EditorConfirmationPrompt struct {
	Token   string
	Field   string
	Value   any
	Message string
	Request *termform.CommitRequest
	Finish  bool
}

EditorConfirmationPrompt is a consequence the user must accept before a save lands. It is not a nicety: `state → DONE` on a parent cascades to its open descendants, and clearing the last date retires the recurrence with it.

type EditorConflict

type EditorConflict struct {
	Field      string
	LocalValue any
	FreshValue any
}

EditorConflict is a same-field external edit caught at save time.

type EditorOutcome

type EditorOutcome struct {
	Status     EditorStatus
	Transition termform.Transition
	Message    string
	// Field is the field an outcome is about, when it is about one.
	Field string
	// Wrote reports that this outcome CHANGED the store. It is separate from
	// the status because a finish and a save both may or may not have written,
	// and the list has to be rebuilt for exactly the ones that did.
	Wrote bool
}

EditorOutcome is one interaction's answer.

func (EditorOutcome) Handled

func (o EditorOutcome) Handled() bool

Handled reports that the editor consumed the input.

type EditorStatus

type EditorStatus string

EditorStatus is the outcome vocabulary one editor interaction produces.

const (
	EditorUnhandled        EditorStatus = "unhandled"
	EditorHandled          EditorStatus = "handled"
	EditorChanged          EditorStatus = "changed"
	EditorFocusChanged     EditorStatus = "focus_changed"
	EditorInvalid          EditorStatus = "invalid"
	EditorConfirmation     EditorStatus = "confirmation"
	EditorConfirmCancelled EditorStatus = "confirmation_cancelled"
	EditorConflicted       EditorStatus = "conflict"
	EditorConflictReloaded EditorStatus = "conflict_reloaded"
	EditorMissing          EditorStatus = "missing"
	EditorFinished         EditorStatus = "finished"
	EditorRefreshed        EditorStatus = "refreshed"
	EditorRevertPending    EditorStatus = "revert_pending"
	EditorReverted         EditorStatus = "reverted"
	EditorSaved            EditorStatus = "saved"
	EditorNoChange         EditorStatus = "no_change"
	EditorQuitReady        EditorStatus = "quit_ready"
	EditorQuitConfirmation EditorStatus = "quit_confirmation"
	EditorQuitConfirmed    EditorStatus = "quit_confirmed"
	EditorQuitCancelled    EditorStatus = "quit_cancelled"
	EditorSuspended        EditorStatus = "suspended"
	EditorCopyKept         EditorStatus = "copy_kept"
)

The editor outcomes.

type ErrIllegalTransition

type ErrIllegalTransition struct{ From, To Mode }

ErrIllegalTransition is what SetMode reports for a move the table forbids.

func (ErrIllegalTransition) Error

func (e ErrIllegalTransition) Error() string

type FieldKind added in v1.11.0

type FieldKind string

FieldKind is which control a field paints.

const (
	// FieldText is a single-line editor.
	FieldText FieldKind = "text"
	// FieldChoice is a list over a RUNTIME vocabulary.
	FieldChoice FieldKind = "choice"
	// FieldTextArea is a wrapped multi-line editor.
	FieldTextArea FieldKind = "text_area"
)

The three field kinds.

type FieldModal added in v1.11.0

type FieldModal struct {

	// Success is the effect to run after a successful submit, set by the submit
	// callback itself, exactly as QuickForm does it.
	Success func()
	// OnAction runs an extra affordance and says what happens next, so a caller
	// can answer "release" with a confirmation of its own, or with an immediate
	// Cancelled that closes the modal. A nil handler makes the actions inert.
	OnAction func(id string) FieldModalOutcome
	// contains filtered or unexported fields
}

FieldModal is the TUI's reusable MULTI-field popup.

QuickForm is the single-field popup: one prompt, one value, one error line. A prompt that needs three different KINDS of answer — a typed name, a choice from a vocabulary the user configured, and a paragraph of instructions — cannot be spelled as one text field without inventing a word grammar, and a word grammar is exactly the thing that made the old delegate prompt dangerous.

What this owns, and what it deliberately does not:

  • It owns focus, per-field validation, the geometry, and the HIT MAP. The hit map is recorded by the paint, not re-derived from the field list, so a pointer cannot reach a cell the box is not currently painting — on either axis. That is the same rule the palettes follow. What the cell MEANT is a separate question, since the vocabulary behind it is a runtime func that can change between the paint and the click; fieldmodalinput.go says how that is resolved.
  • It does not own the vocabulary. A choice field takes a func, called on every render, so a list of modes that comes from user config is read at the moment it is painted rather than baked in when the modal was built.
  • It does not own the mutation. Submit returns a message on refusal and "" on success, so a caller reports its own refusal in its own words.

The editing machinery is termform's: Input and TextArea are the same buffers the task editor uses, including their grapheme handling, their scroll offsets and now their click-to-caret inverse. The choice field is local, because termform.Select spends Return on opening and picking, and in a modal Return belongs to submit.

GEOMETRY IS FIXED AT CONSTRUCTION. Every field reserves its rows — value rows, option rows, and its own hint row — whether or not it currently has anything to say. That is what makes an inline validation error cost zero rows: the error is painted in the hint's slot. Width is measured once, from the whole content, and cached. Neither the box nor its centered position moves while it is being used, which is the Modal invariant restated for a form.

func NewFieldModal added in v1.11.0

func NewFieldModal(options FieldModalOptions) *FieldModal

NewFieldModal builds one. A spec with no key or an unknown kind is dropped rather than painted as a control nothing can focus.

func (*FieldModal) ArmedAction added in v1.14.0

func (f *FieldModal) ArmedAction() string

ArmedAction reports which action is behind its first press, or "".

func (*FieldModal) Cancel added in v1.11.0

func (f *FieldModal) Cancel() FieldModalOutcome

Cancel discards, behind the unsaved-changes latch.

A clean modal closes on the first gesture. A dirty one arms and reports Guarded, and only the SECOND cancel discards — the same two-step the task draft quit confirmation uses, for the same reason: work someone typed is not thrown away by one keystroke.

func (*FieldModal) Click added in v1.11.0

func (f *FieldModal) Click(row, column int) FieldModalOutcome

Click answers a left click at a BOX-RELATIVE row and column.

Everything it needs was recorded by the last paint, so a row that is not on screen cannot be hit and a filtered option list cannot be off by the number of options the filter removed.

BOTH axes are bounded. Bounding only the row was a real hole: a button's span is recorded against its untruncated text, so in a narrow box the span of a button whose label was cut off extended past the border, and a click that landed on the list BEHIND the modal invoked it.

func (*FieldModal) Dirty added in v1.11.0

func (f *FieldModal) Dirty() bool

Dirty reports whether anything differs from what the modal opened with.

func (*FieldModal) DisarmCancel added in v1.11.0

func (f *FieldModal) DisarmCancel()

DisarmCancel drops the armed latch, for a host that interrupted the modal with something the user has since answered. An interruption is input like any other: the arm must not survive it, or the escape AFTER the interruption discards without the confirmation the latch exists to require.

func (*FieldModal) Drag added in v1.14.0

func (f *FieldModal) Drag(row int) FieldModalOutcome

Drag continues an in-flight scrollbar drag: the motion's box row becomes a track row via the track origin captured at press, the grab offset restores the pointer's place within the thumb, and the params are rebuilt LIVE from the field — not trusted from the paint — because the vocabulary behind a choice list is a runtime func and a note may have been edited mid-drag.

func (*FieldModal) EndDrag added in v1.14.0

func (f *FieldModal) EndDrag() bool

EndDrag releases the pointer after a scrollbar drag. It reports whether a drag was actually in flight, so a stray release can fall through.

func (*FieldModal) Error added in v1.11.0

func (f *FieldModal) Error() string

Error is the host's refusal message.

func (*FieldModal) FieldError added in v1.11.0

func (f *FieldModal) FieldError(key string) string

FieldError is one field's inline validation message.

func (*FieldModal) FocusKey added in v1.11.0

func (f *FieldModal) FocusKey() string

FocusKey is the focused field's key, or "" for an empty modal.

func (*FieldModal) HandleKey added in v1.11.0

func (f *FieldModal) HandleKey(sequence string) FieldModalOutcome

HandleKey routes one raw key sequence.

func (*FieldModal) Height added in v1.11.0

func (f *FieldModal) Height() int

Height is the box's natural height: every field's fixed rows, the status row, the buttons, the key chips, plus the border. A caller clamps it to the terminal; nothing about the content changes it.

func (*FieldModal) Keys added in v1.11.0

func (f *FieldModal) Keys() []string

Keys is the field order.

func (*FieldModal) Kind added in v1.11.0

func (f *FieldModal) Kind() FieldModalKind

Kind, Title, TargetID and ReturnMode are the read accessors a host needs.

func (*FieldModal) Options added in v1.11.0

func (f *FieldModal) Options(key string) []FieldOption

Options is a choice field's vocabulary as of right now.

func (*FieldModal) Paste added in v1.11.0

func (f *FieldModal) Paste(text string) FieldModalOutcome

Paste inserts pasted text into the focused field. Pasted newlines are text in a note and are sanitized away by a single-line editor; neither is ever a command.

func (*FieldModal) PendingCancel added in v1.11.0

func (f *FieldModal) PendingCancel() bool

PendingCancel reports the armed unsaved-changes latch.

func (*FieldModal) Render added in v1.11.0

func (f *FieldModal) Render(styler Styler, maxWidth, maxHeight int) FieldModalRender

Render paints the modal into a bordered box no larger than the budget, and records the hit map the pointer methods read.

func (*FieldModal) ReturnMode added in v1.11.0

func (f *FieldModal) ReturnMode() ReturnMode

func (*FieldModal) SetArmedAction added in v1.14.0

func (f *FieldModal) SetArmedAction(id string) bool

SetArmedAction marks one of the modal's actions as standing behind its first press: its button inverts to the armed look and, while armed, the box border reads as warning — the same news in two places. Arming without a matching action id reports false and changes nothing.

func (*FieldModal) SetError added in v1.11.0

func (f *FieldModal) SetError(message string)

SetError posts a host refusal without closing the modal. Posting any refusal disarms an armed action: the armed button and the confirmation message it armed are ONE story, and a refusal that overwrote the message while the button stayed inverted would be an armed look with nothing behind it. A caller that is arming — posting the confirmation — calls SetArmedAction after.

func (*FieldModal) SetFieldError added in v1.11.0

func (f *FieldModal) SetFieldError(key, message string) bool

SetFieldError posts a host refusal against one field, so a rejection about the mode is painted under the mode rather than at the bottom of the box.

func (*FieldModal) SetFocus added in v1.11.0

func (f *FieldModal) SetFocus(key string) bool

SetFocus moves focus to a named field, reporting whether it exists.

func (*FieldModal) SetValue added in v1.11.0

func (f *FieldModal) SetValue(key, value string) bool

SetValue writes a field from the host.

func (*FieldModal) Submit added in v1.11.0

func (f *FieldModal) Submit() FieldModalOutcome

Submit validates every field and then runs the caller's mutation. Validation runs first and a failure never reaches the host: asking a host to write a value the modal already knows is wrong just produces a worse error message, and focus lands on the first offending field so the user is looking at it.

func (*FieldModal) TargetID added in v1.11.0

func (f *FieldModal) TargetID() string

func (*FieldModal) Title added in v1.11.0

func (f *FieldModal) Title() string

func (*FieldModal) Value added in v1.11.0

func (f *FieldModal) Value(key string) string

Value is one field's current value.

func (*FieldModal) Values added in v1.11.0

func (f *FieldModal) Values() map[string]string

Values is every field's value.

func (*FieldModal) Wheel added in v1.11.0

func (f *FieldModal) Wheel(row, column, direction int) FieldModalOutcome

Wheel answers one wheel tick at a box-relative row. Direction is -1 for up.

A tick over a choice list scrolls the OFFERED options without changing the selection, and a tick over a note scrolls the note by moving the caret a line — the same motion the arrow keys make, so the two never disagree about where the text is.

type FieldModalAction added in v1.11.0

type FieldModalAction struct {
	ID    string
	Label string
	// Key is the raw sequence that invokes it, e.g. "\x12" for ctrl-r.
	Key string
	// KeyLabel is how that key is spelled on the button.
	KeyLabel string
}

FieldModalAction is an extra affordance — release, undelegate — with both a key and a button. A caller that needs a confirmation runs it on the outcome; the component does not decide what is destructive enough to confirm.

type FieldModalKind added in v1.11.0

type FieldModalKind string

FieldModalKind names which multi-field modal is open, so a test and a hit test can both say which popup they mean.

const (
	FieldModalDelegate FieldModalKind = "delegate"
	FieldModalGeneric  FieldModalKind = "generic"
)

The multi-field modals this build has. The delegate modal belongs to its own packet; the fixture kind is the general-purpose one the tests drive.

type FieldModalOptions added in v1.11.0

type FieldModalOptions struct {
	Kind        FieldModalKind
	Title       string
	Fields      []FieldSpec
	Actions     []FieldModalAction
	SubmitLabel string
	CancelLabel string
	MinWidth    int
	TargetID    string
	ReturnMode  ReturnMode
	// Submit returns "" on success and a user-visible message on refusal.
	Submit func(values map[string]string) string
}

FieldModalOptions builds a FieldModal.

type FieldModalOutcome added in v1.11.0

type FieldModalOutcome struct {
	Result   FieldModalResult
	ActionID string
}

FieldModalOutcome is a result plus, for an action, which one.

type FieldModalRender added in v1.11.0

type FieldModalRender struct {
	Lines []string
	// FocusedContentRow is the row within Lines carrying the caret, or -1.
	FocusedContentRow int
	Width             int
}

FieldModalRender is a painted modal.

type FieldModalResult added in v1.11.0

type FieldModalResult string

FieldModalResult is what one gesture did.

const (
	FieldModalHandled   FieldModalResult = "handled"
	FieldModalChanged   FieldModalResult = "changed"
	FieldModalGuarded   FieldModalResult = "guarded"
	FieldModalCancelled FieldModalResult = "cancelled"
	FieldModalSubmitted FieldModalResult = "submitted"
	FieldModalError     FieldModalResult = "error"
	FieldModalActioned  FieldModalResult = "action"
)

The outcomes. Guarded is the armed unsaved-changes latch: nothing has been discarded yet, and the caller should keep the modal open.

type FieldOption added in v1.11.0

type FieldOption struct {
	Value string
	Label string
}

FieldOption is one entry in a choice field's vocabulary.

type FieldSpec added in v1.11.0

type FieldSpec struct {
	Key   string
	Label string
	Kind  FieldKind
	// Hint is the steady guidance shown under the field. An inline validation
	// error replaces it in place, so neither ever changes the row count.
	Hint    string
	Initial string
	// Options is the runtime vocabulary, re-read on every render. Nil is an
	// empty vocabulary, which a choice field renders as "(no options available)"
	// rather than as a missing control.
	Options func() []FieldOption
	// FreeText lets a choice field keep typed text that matches no option,
	// which is how "pick a known assignee OR type an address" is one field
	// instead of two.
	FreeText bool
	// Rows is a text area's height; VisibleOptions is a choice list's. Both
	// have defaults and both are fixed for the life of the modal.
	Rows           int
	VisibleOptions int
	// Validate is the field's own rule, returning "" when the value is fine.
	Validate func(value string) string
}

FieldSpec declares one field.

type FormRender

type FormRender struct {
	Lines []string
	// FocusedContentRow is the row, within Lines' content area, that holds the
	// caret — what a host needs to place a real terminal cursor. -1 when the
	// focused row scrolled out of view.
	FocusedContentRow int
}

FormRender is a rendered form box.

func RenderForm

func RenderForm(styler Styler, request FormRenderRequest) FormRender

RenderForm paints a TermForm render model into a bordered box.

It is a pure function of the request: no terminal, no cursor addressing, no clock. That is what makes the fixed-size render fixtures in the tests meaningful — the same request produces the same bytes on every machine.

type FormRenderRequest

type FormRenderRequest struct {
	Model  termform.RenderModel
	Width  int
	Height int
	Title  string
	Hint   string
	// Error is a host-level failure — a rejected save — which outranks the
	// form's own validation messages, because it is the newer news.
	Error  string
	Suffix string
}

FormRenderRequest is everything a render needs. The caller supplies the WHOLE cell budget; this renderer never samples terminal geometry.

type Group

type Group struct {
	Key   string
	Nodes []*taskquery.Node
}

Group is one named bucket of nodes, already sorted.

type IntakeCounts

type IntakeCounts struct {
	Inbox     int
	Approvals int
}

IntakeCounts is what the Inbox tab badge and its section headers advertise.

type KeyChip added in v1.14.0

type KeyChip struct {
	Key   string // e.g. "tab", "ctrl-s", "↑↓"
	Label string // e.g. "next"
}

KeyChip is one advertised binding.

type LayoutRequest

type LayoutRequest struct {
	Width        int
	Height       int
	Footer       []string
	Selected     int
	HasSelection bool
	Panel        bool
	PanelMode    string
	PanelOffset  int
	Editing      bool
}

LayoutRequest is what a caller knows before geometry is computed.

type LinkPicker added in v1.7.0

type LinkPicker struct {
	// contains filtered or unexported fields
}

LinkPicker is the single-choice adapter over a task's openable link union.

func NewLinkPicker added in v1.7.0

func NewLinkPicker(styler Styler, targetID string, found []links.Link) *LinkPicker

NewLinkPicker builds a searchable picker whose visible row favors a label while retaining the system and URL needed to distinguish similar choices.

func (*LinkPicker) HandleKey added in v1.7.0

func (p *LinkPicker) HandleKey(key string) PickerResult

HandleKey adds bounded, query-free digit selection to the shared picker. A digit that does not name a result remains ordinary searchable input.

func (*LinkPicker) Hit added in v1.7.0

func (p *LinkPicker) Hit(rowOffset int) PickerResult
func (p *LinkPicker) Link(result PickerResult) (links.Link, bool)

Link resolves an accepted URL back to its classified link payload.

func (*LinkPicker) Move added in v1.7.0

func (p *LinkPicker) Move(delta int) PickerResult

func (*LinkPicker) Paste added in v1.7.0

func (p *LinkPicker) Paste(text string) PickerResult

func (*LinkPicker) Picker added in v1.7.0

func (p *LinkPicker) Picker() *ChoicePicker

Picker exposes the shared picker for rendering and tests.

func (*LinkPicker) TargetID added in v1.7.0

func (p *LinkPicker) TargetID() string

TargetID is the stable task the choices came from.

type Modal struct {
	// contains filtered or unexported fields
}

Modal is one open overlay: content, scroll position, and an optional live line filter.

Three invariants it keeps for itself, all of them about NOT MOVING:

  • the box width comes from the FULL content, title included, so scrolling or filtering never resizes it;
  • View never yields more rows than fit — the border takes two rows of the body and the status line one more;
  • while a filter is active the box keeps its full unfiltered height, so neither the box nor its centered position jumps as matches come and go.

A modal that resized while you typed into it would be unusable for the one thing filtering is for: reading a long list while narrowing it.

func NewModal

func NewModal(options ModalOptions) *Modal

NewModal builds one. Filter metadata that does not align with the lines is dropped rather than honoured, because a misaligned map would hide the wrong lines — silently.

func (*Modal) AllLines

func (m *Modal) AllLines() []string

AllLines is the unfiltered content.

func (*Modal) Filter

func (m *Modal) Filter() string

func (*Modal) Filterable

func (m *Modal) Filterable() bool

Filterable reports whether `/` opens a line filter on this modal.

func (*Modal) Kind

func (m *Modal) Kind() ModalKind

func (*Modal) Lines

func (m *Modal) Lines() []string

Lines is the content after the filter, or all of it when none is active.

func (*Modal) Replace

func (m *Modal) Replace(title string, lines []string, filterGroups []string, filterContextLines []bool)

Replace swaps live content without discarding the user's filter or scroll intent. The next View clamps scroll against the refreshed match set.

func (*Modal) Scroll

func (m *Modal) Scroll() int

func (*Modal) ScrollHalf

func (m *Modal) ScrollHalf(direction, bodyHeight int)

func (*Modal) ScrollLine

func (m *Modal) ScrollLine(delta, bodyHeight int)

ScrollLine, ScrollHalf and ScrollPage are the three scroll gestures.

func (*Modal) ScrollPage

func (m *Modal) ScrollPage(direction, bodyHeight int)

func (*Modal) SetFilter

func (m *Modal) SetFilter(query string)

SetFilter applies a query. An unchanged query keeps the memo AND the scroll position, so a repeated keystroke does not throw the reader back to the top.

func (*Modal) Title

func (m *Modal) Title() string

Title, Kind, Scroll and Filter are the read accessors.

func (*Modal) View

func (m *Modal) View(styler Styler, bodyHeight int, filterLine string) ModalView

View is the window at the current scroll, at most bodyHeight-2 lines so the boxed result fits the body. A non-empty filterLine — or an active filter — switches to the fixed-height filtered view.

func (*Modal) Viewport

func (m *Modal) Viewport(bodyHeight int) int

Viewport is how many content rows are visible at once inside body rows. A filter pins the query line to the top and the count to the bottom, so two fewer content rows are available while one is active.

func (*Modal) Width

func (m *Modal) Width(styler Styler) int

Width is the box width from the full, unfiltered content. The frame clamps it to the terminal.

type ModalButton added in v1.14.0

type ModalButton struct {
	ID    string
	Label string
	// KeyLabel names the key that also invokes the button, so the mouse path
	// advertises the keyboard path instead of hiding it. Empty for none.
	KeyLabel string
	Variant  ButtonVariant
}

ModalButton is one clickable affordance in a modal's action row.

func (ModalButton) Width added in v1.14.0

func (b ModalButton) Width(styler Styler) int

Width is the display width of the button's text in cells.

type ModalButtonSpan added in v1.14.0

type ModalButtonSpan struct {
	Begin, End int
	ID         string
}

ModalButtonSpan is one painted button's column range within its row.

func PaintButtonRow added in v1.14.0

func PaintButtonRow(styler Styler, buttons []ModalButton) (string, []ModalButtonSpan)

PaintButtonRow lays buttons out left to right with one-cell gaps and returns the line plus each button's [begin,end) column span, so a click resolves to an ID without re-derifying layout. Spans index into the RETURNED string directly: cell Begin is where PaintModalButton's text starts. A caller that splices the row into a bordered box adds its own border offset when it maps a pointer column to a span — this function never guesses where the line will sit.

type ModalContent

type ModalContent struct {
	Title              string
	Lines              []string
	FilterGroups       []string
	FilterContextLines []bool
}

ModalContent is a built overlay body: what a Modal is constructed from.

func HelpContent

func HelpContent(styler Styler, modes record.ModeVocabulary) ModalContent

HelpContent is the `?` overlay, generated ENTIRELY from the shortcut registry, for the delegation mode vocabulary this store enforces.

The vocabulary is a parameter because the registry cannot hold one: it is built during init, before any store exists. The overlay is where a user goes to LEARN the keys, so quoting the built-in modes here while the delegate modal and the delegate refusal quoted the configured ones would make the two places a user looks disagree about the same word.

Generating it is the whole point: a hand-written help list is a second source of truth that goes stale the first time a binding moves, and a task list whose help lies about its keys is worse than one with no help at all.

The filter groups are the section titles, so filtering the modal keeps a matched binding's heading visible — a bare "x archive" with no section above it does not tell you where the key works.

type ModalKind

type ModalKind string

ModalKind names what an overlay is for. The kind decides which keys the modal answers, so a confirmation cannot be dismissed by the key that scrolls help — and, more importantly, `y` cannot mean "archive" while a help modal is open.

const (
	ModalHelp                   ModalKind = "help"
	ModalArchiveConfirm         ModalKind = "archive_confirm"
	ModalArchiveBlocked         ModalKind = "archive_blocked"
	ModalDeleteConfirm          ModalKind = "delete_confirm"
	ModalDeleteCascadeConfirm   ModalKind = "delete_cascade_confirm"
	ModalProjectCompleteConfirm ModalKind = "project_complete_confirm"
	ModalProjectArchiveConfirm  ModalKind = "project_archive_confirm"
	ModalUnsupportedSchema      ModalKind = "unsupported_schema"
	ModalTaskDraftQuitConfirm   ModalKind = "task_draft_quit_confirm"
	ModalFieldModalQuitConfirm  ModalKind = "field_modal_quit_confirm"
	ModalAgentQuitConfirm       ModalKind = "agent_quit_confirm"
	ModalAgentActivity          ModalKind = "agent_activity"
	ModalAgentQueueCancel       ModalKind = "agent_queue_cancel_confirm"
)

The modal kinds this build has.

type ModalOptions

type ModalOptions struct {
	Title              string
	Lines              []string
	Kind               ModalKind
	Filterable         bool
	FilterGroups       []string
	FilterContextLines []bool
}

ModalOptions builds a Modal.

type ModalView

type ModalView struct {
	Title string
	Lines []string
	Width int
}

ModalView is the window the frame draws.

type Mode

type Mode string

Mode is the interaction mode. The shell implements list and filter; the remaining modes are the seams the editor/forms/modals packet and the rendering/agent packet plug into. They are NAMED here rather than invented later so the two halves agree on the vocabulary at integration, and so an unimplemented mode is a visible absence rather than a silent branch.

const (
	ModeList           Mode = "list"
	ModePrompt         Mode = "prompt"
	ModeFilter         Mode = "filter"
	ModeModal          Mode = "modal"
	ModeForm           Mode = "form"
	ModePalette        Mode = "palette"
	ModeContextPalette Mode = "context_palette"
	ModeLinkPicker     Mode = "link_picker"
	ModeTaskEdit       Mode = "task_edit"
)

The modes, in the order lib/tui/ui_state.rb declares them.

const ModeFieldModal Mode = "field_modal"

ModeFieldModal is the multi-field popup's mode.

It is a mode of its own rather than a flag on ModeForm because the key routing genuinely differs: tab moves between fields, Return is text inside a note, and escape has a latch in front of it. Sharing ModeForm would mean the single-field popups inherited all three.

const ModeModalFilter Mode = "modal_filter"

ModeModalFilter is the live line filter inside a filterable modal. It is a mode of its own rather than a flag on ModeModal because the key routing is genuinely different: while it is active, `j` types a letter instead of scrolling.

type Model

type Model struct {
	// contains filtered or unexported fields
}

Model is the Bubble Tea root — the port of Tui::App's state, minus its event loop.

STRUCTURAL CHANGE from Ruby, deliberate and worth naming: Ruby's App is one 3,500-line object that owns the terminal, the read model, every key handler, and every cache, and invalidates the caches by hand from twenty places. Here the read model is rebuilt into `rows` by ONE function (refreshRows) from ONE value (BuildRequest), so there is no cache to invalidate and no way for two caches to disagree. Ruby needed the caches because it repainted on a 0.25s tick whether or not anything changed; Bubble Tea only calls View after an Update, so the pressure that justified them is gone.

func New

func New(options Options) *Model

New builds the model from saved session state and one application facade.

func NewRuntime added in v1.1.0

func NewRuntime(options RuntimeOptions) (*Model, error)

NewRuntime wires the application, store, renderer, opener, provider list, and agent queue used by every shipping TUI host.

func (*Model) ActionPalette

func (m *Model) ActionPalette() *ActionPalette

ActionPalette is the open action palette, or nil.

func (*Model) AgentEntries

func (m *Model) AgentEntries() []AgentEntry

AgentEntries is the ordered provider/model list, for the same reason.

func (*Model) ApplyContextFilter

func (m *Model) ApplyContextFilter(contexts []string)

ApplyContextFilter adopts an accepted context set and rebuilds the rows.

func (*Model) ApproveAndCompleteProposal added in v1.11.0

func (m *Model) ApproveAndCompleteProposal()

ApproveAndCompleteProposal is `c` on a proposed task: the proposal is accepted and the accepted task is completed, in ONE undoable step.

It is the honest answer to a proposal for work that is already finished. Rejecting would clear the row too, but it records a decline — the wrong history, and the wrong signal to whoever proposed it.

func (*Model) ArchiveSweep

func (m *Model) ArchiveSweep()

ArchiveSweep is `x`: preview what a sweep would move, then ask.

It never sweeps directly. The preview the user is shown is PINNED and handed back on confirmation, so a list that changed while the modal was open refuses rather than archiving a set nobody saw.

func (*Model) BumpPriority

func (m *Model) BumpPriority(delta int)

BumpPriority is `K` / `J`: one step along the ladder, never past its end.

func (*Model) CancelQueuedAgentRequests

func (m *Model) CancelQueuedAgentRequests()

CancelQueuedAgentRequests is the palette action behind the confirmation.

func (*Model) CaptureIntoProject

func (m *Model) CaptureIntoProject()

CaptureIntoProject is `a` on a project header: append a new TODO to it.

func (*Model) ClearQuitRequest added in v1.1.0

func (m *Model) ClearQuitRequest()

ClearQuitRequest acknowledges an embedded quit request.

func (*Model) CloseActionPalette

func (m *Model) CloseActionPalette()

CloseActionPalette dismisses it, returning where it came from.

func (*Model) CloseContextPalette

func (m *Model) CloseContextPalette()

CloseContextPalette dismisses it.

func (*Model) CloseFieldModal added in v1.11.0

func (m *Model) CloseFieldModal(success bool)

CloseFieldModal dismisses it, running the success effect on a successful submit exactly as CloseForm does.

func (*Model) CloseForm

func (m *Model) CloseForm(success bool)

CloseForm dismisses the quick form, running its success effect on a successful submit.

func (*Model) CloseModal

func (m *Model) CloseModal()

CloseModal dismisses the overlay.

func (*Model) ClosePanel

func (m *Model) ClosePanel()

ClosePanel closes the right panel.

func (*Model) CloseTaskEdit

func (m *Model) CloseTaskEdit(message string)

CloseTaskEdit leaves the editor.

func (*Model) CollapseAll

func (m *Model) CollapseAll()

CollapseAll folds every foldable node, across the whole tree. In the outline that includes sections, so H collapses the view down to its headings — the overview an outliner's fold-all exists for. The selection may have been on a now-hidden row, so rows are rebuilt and the selection reconciled.

func (*Model) CollapseSelected

func (m *Model) CollapseSelected()

CollapseSelected folds the selected subtree — a task's or, in the outline, a section's. On an expandable, not-yet-folded node it folds and keeps the cursor there; otherwise it climbs to the parent row, so a second press walks up the tree.

func (*Model) CommandAvailable added in v1.1.0

func (m *Model) CommandAvailable(id string) (bool, error)

CommandAvailable reports whether a command exists in the current focus context and its live availability predicate passes.

func (*Model) CompleteSelected

func (m *Model) CompleteSelected()

CompleteSelected is `c`: close the selected task, or confirm closing a whole project when a project header is selected.

func (*Model) ConfirmArchiveProject

func (m *Model) ConfirmArchiveProject(project *taskquery.ProjectView)

ConfirmArchiveProject asks before archiving a whole section subtree, surfacing any open work it would take with it.

func (*Model) ConfirmCompleteProject

func (m *Model) ConfirmCompleteProject(project *taskquery.ProjectView)

ConfirmCompleteProject asks before closing every open task in a section.

func (*Model) ConsumesTextInput added in v1.1.0

func (m *Model) ConsumesTextInput() bool

ConsumesTextInput reports whether printable keys belong to an input buffer.

func (*Model) ContextFilters

func (m *Model) ContextFilters() []string

ContextFilters is the active `@` filter set.

func (*Model) ContextPalette

func (m *Model) ContextPalette() *ContextPalette

ContextPalette is the open context palette, or nil.

func (*Model) CurrentEntry

func (m *Model) CurrentEntry() AgentEntry

CurrentEntry is the provider/model new requests go to.

func (*Model) CurrentItem

func (m *Model) CurrentItem() *store.Item

CurrentItem is the selected task, or nil on a header or project row.

func (*Model) CurrentProject

func (m *Model) CurrentProject() *taskquery.ProjectView

CurrentProject is the selected project header's view, or nil.

func (*Model) CurrentSpatialFocus added in v1.12.0

func (m *Model) CurrentSpatialFocus() SpatialFocus

CurrentSpatialFocus reports a visible stop. A closed or responsively hidden detail panel always projects to list rather than exposing a stale target.

func (*Model) CurrentView added in v1.1.0

func (m *Model) CurrentView() string

CurrentView is the stable active view key.

func (*Model) CyclePanelMode

func (m *Model) CyclePanelMode(delta int)

CyclePanelMode steps the panel width ladder.

func (*Model) CycleView

func (m *Model) CycleView(delta int)

CycleView moves by tabs, wrapping.

func (*Model) DecideProposal

func (m *Model) DecideProposal(action application.ProposalAction)

DecideProposal is `a` / `r` on a proposed task.

func (*Model) DeferSelected

func (m *Model) DeferSelected()

DeferSelected is `z`, the OmniFocus-style availability action.

A fuzzy date atomically sets the available-from date AND clears this task's own hold; `someday` adds the indefinite marker; `now` clears only the blockers this task itself owns. All three are one changeset, so one keystroke costs one undo and no intermediate state is observable.

func (*Model) DelegateSelected

func (m *Model) DelegateSelected()

DelegateSelected is `D`.

Every part of the delegation is stated in its own control and submitted as ONE application.DelegationCommand: the modal composes nothing, so who holds the task, in what mode, and what they were asked to do are one write and one undo step.

func (*Model) DeleteSelected added in v1.1.0

func (m *Model) DeleteSelected()

DeleteSelected is `#` / Delete: preview a hard delete, then confirm.

It never writes on the first keystroke. A leaf gets a simple confirm; a task with descendants gets a cascade confirm that names counts. Both refuse projects/sections (store rule: delete targets tasks) and both land in one journal step that `u` / ctrl-r already undo/redo.

func (*Model) DismissResponse

func (m *Model) DismissResponse()

DismissResponse closes the pane.

func (*Model) ExpandAll

func (m *Model) ExpandAll()

ExpandAll unfolds everything.

func (*Model) ExpandSelected

func (m *Model) ExpandSelected()

ExpandSelected unfolds the selected node if it is folded.

func (*Model) FieldModal added in v1.11.0

func (m *Model) FieldModal() *FieldModal

FieldModal is the open multi-field modal, or nil.

func (*Model) Flash

func (m *Model) Flash(message string)

Flash shows a transient status message.

func (*Model) FlashMessage

func (m *Model) FlashMessage() string

FlashMessage is the live flash, or "".

func (*Model) FocusContext added in v1.1.0

func (m *Model) FocusContext() string

FocusContext is a stable host-facing name for the active interaction layer.

func (*Model) FocusPrompt

func (m *Model) FocusPrompt()

FocusPrompt is `tab`.

func (*Model) Footer

func (m *Model) Footer() []string

Footer is the status rows under the list, in Ruby's order.

The order is the contract, not an accident. A running agent's transcript takes the top because it is the only thing on screen that is still changing; the prompt takes the bottom because it is where the caret is. And the prompt is SKIPPED in the modes that render their own input in an overlay, so a short terminal never shows two carets.

suppressFooter drops the whole stack; suppressKeyHints drops only the last row of it. See footerForMode.

func (*Model) Form

func (m *Model) Form() *QuickForm

Form is the open quick form, or nil.

func (*Model) HandleMouse

func (m *Model) HandleMouse(event tea.MouseMsg) bool

HandleMouse routes one mouse event. It reports whether the event was consumed, so the integration owner can layer a hit map above it without double-handling.

func (*Model) Header

func (m *Model) Header(width int) string

Header is the tab strip plus the counts.

func (*Model) Init

func (m *Model) Init() tea.Cmd

Init starts the file-watch tick.

func (*Model) InvokeCommand added in v1.1.0

func (m *Model) InvokeCommand(id string) (tea.Cmd, error)

InvokeCommand executes one exact semantic command without replaying an ambiguous default key.

func (*Model) Layout

func (m *Model) Layout() ScreenLayout

Layout exposes the geometry for tests and for the hit map the rendering packet builds.

func (*Model) LinkOpener

func (m *Model) LinkOpener() Opener

LinkOpener is the injected launcher, or nil. It is exported so the entry point's own test can prove the shipping constructor wired one — the defect that made every valid link refuse in the real binary while the fake-injected model tests stayed green.

func (*Model) LinkPicker added in v1.7.0

func (m *Model) LinkPicker() *LinkPicker

LinkPicker is the open task-link picker, or nil.

func (*Model) MarkNextSelected added in v1.15.0

func (m *Model) MarkNextSelected()

MarkNextSelected is `N`: promote the selected open task to NEXT so it lands on the Next tab, in ONE undo step.

It does not toggle. `N` means "this is a next action", and a second press leaves it one — a key that quietly demoted the task back to TODO would make the state depend on how many times it had been pressed, which is not something the row shows.

func (*Model) Modal

func (m *Model) Modal() *Modal

Modal is the open overlay, or nil.

func (*Model) ModalFilterInput

func (m *Model) ModalFilterInput() string

ModalFilterInput is the text in the modal's filter line.

func (*Model) ModalStartFilter

func (m *Model) ModalStartFilter()

ModalStartFilter opens the live line filter inside a filterable modal.

func (*Model) Mode

func (m *Model) Mode() Mode

Mode is the current interaction mode.

func (*Model) MouseEnabled

func (m *Model) MouseEnabled() bool

MouseEnabled reports whether the resolved config asks for mouse reporting. The entry point reads it so View can set MouseMode each frame; turning mouse tracking on takes the terminal's own text selection away from the user.

func (*Model) OpenActionPalette

func (m *Model) OpenActionPalette()

OpenActionPalette shows every action available right now.

func (*Model) OpenAgentActivity

func (m *Model) OpenAgentActivity()

OpenAgentActivity is `A`.

func (*Model) OpenContextPalette

func (m *Model) OpenContextPalette()

OpenContextPalette shows the @context filter picker.

func (*Model) OpenDatePopup

func (m *Model) OpenDatePopup()

OpenDatePopup is `d`: reschedule the task's own date — the deadline when it has one, otherwise the available-from date, and a new deadline when it has neither. On a section row it edits the section's hard-landscape date range instead — see openSectionDatesPopup.

func (*Model) OpenDetail

func (m *Model) OpenDetail()

OpenDetail opens the panel on the selection, or closes it if it is already showing that selection.

func (*Model) OpenFieldModal added in v1.11.0

func (m *Model) OpenFieldModal(modal *FieldModal) bool

OpenFieldModal opens a multi-field modal.

It is the ONE entry point a feature needs: build a FieldModal from specs and hand it over. What the fields MEAN is known only to the caller that declared them, which is what makes the component reusable rather than one feature's prompt wearing a general-sounding name.

func (*Model) OpenHelp

func (m *Model) OpenHelp()

OpenHelp shows the generated shortcut overlay.

func (m *Model) OpenLink()

OpenLink is `o`: open one link immediately or let the user choose among many.

func (*Model) OpenModal

func (m *Model) OpenModal(content ModalContent, kind ModalKind, filterable bool)

OpenModal opens an overlay and enters modal mode.

func (*Model) OpenRecurPopup

func (m *Model) OpenRecurPopup()

OpenRecurPopup is `r`: set or clear a recurrence, with a LIVE gloss of what the typed cookie means as the hint.

A recurrence rides a date stamp, so a task with no date cannot repeat. That is refused BEFORE the popup opens rather than after it is filled in: a form whose every submission must fail is worse than no form.

func (*Model) OpenTaskCount

func (m *Model) OpenTaskCount() int

OpenTaskCount is the header's "N open".

func (*Model) OverdueTaskCount added in v1.8.0

func (m *Model) OverdueTaskCount() int

OverdueTaskCount is the header's "N overdue": open, available tasks whose primary date has already passed. It counts across the whole store, not the current view — the header describes what is true, not what is on screen.

func (*Model) Overlay

func (m *Model) Overlay() *OverlayBox

Overlay is the popup the current mode wants painted, or nil.

func (*Model) Panel

func (m *Model) Panel() *RightPanel

Panel is the open right panel, or nil.

func (*Model) PasteRef

func (m *Model) PasteRef()

PasteRef is `p`: quote the selected task's stable reference into the prompt.

It is QUOTED because a bare id in a sentence is ambiguous to a model and to a human reading the transcript later; the quotes say "this is a handle".

func (*Model) PromptLines

func (m *Model) PromptLines(width int) []string

PromptLines is the prompt row, or the hint that names the key that opens it.

func (*Model) PromptPaste

func (m *Model) PromptPaste(text string)

PromptPaste inserts bracketed-pasted text, from the prompt or from a modal.

func (*Model) PromptText

func (m *Model) PromptText() string

PromptText is what the user has typed.

func (*Model) PumpQueue

func (m *Model) PumpQueue()

PumpQueue is the per-tick drain: read whatever the running process produced, and pick up the next request when one finishes.

func (*Model) Queue

func (m *Model) Queue() *agent.Queue

Queue is the request queue, or nil when the model was built without one.

func (*Model) QuitRequested added in v1.1.0

func (m *Model) QuitRequested() bool

QuitRequested reports an embedded quit request without terminating its host.

func (*Model) ReadError added in v1.2.0

func (m *Model) ReadError() error

ReadError is the sticky store-read failure, or nil when the last read was healthy. An empty store is healthy; see reportFormatErrors.

func (*Model) ReadModel

func (m *Model) ReadModel() *application.ReadModel

ReadModel is the model's current read, for tests and for the packets that need the same snapshot the list was built from.

func (*Model) RedoLast

func (m *Model) RedoLast()

func (*Model) Refresh

func (m *Model) Refresh()

Refresh rebuilds the read model and the rows from it. It is the ONLY path that changes what the list shows, so a refresh caused by an external write and a refresh caused by a keypress cannot behave differently.

func (*Model) RefreshRows

func (m *Model) RefreshRows()

RefreshRows rebuilds the row list from the current read model, then reconciles the selection against it.

func (*Model) RenameProject

func (m *Model) RenameProject()

RenameProject is `e` on a project header.

func (*Model) Render

func (m *Model) Render() string

Render composes one frame at the model's current size.

func (*Model) ReorderSelected

func (m *Model) ReorderSelected(action string)

ReorderSelected moves the selected subtree.

The placement is computed from the SIBLING LIST rather than from screen rows: the rows are a filtered, sorted projection, and moving a task by what is drawn above it would move it somewhere else entirely in the file.

func (*Model) ResizePanel

func (m *Model) ResizePanel(delta int)

ResizePanel nudges the panel by whole columns on top of its mode width.

func (*Model) ResponseLines

func (m *Model) ResponseLines() []string

ResponseLines is the visible window of the response pane.

func (*Model) RestoreRejected added in v1.9.0

func (m *Model) RestoreRejected()

RestoreRejected is `a` on a revealed rejected row: the decline is undone in place and the proposal is back in the queue above it, same id and same text.

func (*Model) Rows

func (m *Model) Rows() []Row

Rows is the current row list.

func (*Model) Save

func (m *Model) Save()

Save persists the session. Best effort — a read-only state directory must not keep the TUI from exiting.

func (*Model) ScrollResponse

func (m *Model) ScrollResponse(delta int)

ScrollResponse is pgup/pgdn over the response pane.

func (*Model) Selected

func (m *Model) Selected() int

Selected is the current row index.

func (*Model) SelectedID

func (m *Model) SelectedID() string

SelectedID is the durable identity the cursor follows.

func (*Model) SessionState

func (m *Model) SessionState() SessionState

SessionState is the state to persist on exit. The collapsed set and the context filters are intersected with what the store actually still holds, so a saved id for a deleted task cannot accumulate forever.

func (*Model) SetActionPalette

func (m *Model) SetActionPalette(palette *ActionPalette)

SetActionPalette opens or clears the action palette.

func (*Model) SetContextPalette

func (m *Model) SetContextPalette(palette *ContextPalette)

SetContextPalette opens or clears the context palette.

func (*Model) SetFieldModal added in v1.11.0

func (m *Model) SetFieldModal(modal *FieldModal)

SetFieldModal opens or clears the overlay without changing the mode, for the same reasons SetForm exists: an external reload may remove it.

func (*Model) SetForm

func (m *Model) SetForm(form *QuickForm)

SetForm opens or clears the quick-form popup.

func (*Model) SetLinkPicker added in v1.7.0

func (m *Model) SetLinkPicker(picker *LinkPicker)

SetLinkPicker opens or clears the task-link picker.

func (*Model) SetModal

func (m *Model) SetModal(modal *Modal)

SetModal opens or clears the modal overlay.

func (*Model) SetMode

func (m *Model) SetMode(target Mode) error

SetMode moves to a mode, refusing a move the table forbids or whose overlay is missing.

The overlay checks are not defensive noise. Ruby raises here, and it raises because every one of these has been reachable: a modal dismissed by an external refresh while a palette opened over it, a form whose return mode points at a modal that is gone. Failing loudly at the transition is what keeps those from becoming a frozen screen.

func (*Model) SetSpatialFocus added in v1.12.0

func (m *Model) SetSpatialFocus(focus SpatialFocus) bool

SetSpatialFocus focuses one visible stop directly. An input or overlay keeps ownership until it closes; a host must not use this seam to reach behind it.

func (*Model) SetTaskEditor

func (m *Model) SetTaskEditor(editor *TaskEditorSession)

SetTaskEditor opens or clears the durable task editor.

func (*Model) SetWorkRefSelected

func (m *Model) SetWorkRefSelected()

SetWorkRefSelected is `W`.

It refuses an undelegated task UP FRONT rather than opening a prompt whose every input must fail — the same shape as `r` refusing an undated task.

func (*Model) ShowUnsupportedSchemaNotice

func (m *Model) ShowUnsupportedSchemaNotice()

ShowUnsupportedSchemaNotice opens the one modal that has no action: nothing this build can do makes a future schema readable.

func (*Model) StartTaskEdit

func (m *Model) StartTaskEdit(focus string)

StartTaskEdit is `e` in the detail panel: open the durable editor on the selected task, focused on one field.

func (*Model) SubmitPrompt

func (m *Model) SubmitPrompt()

SubmitPrompt enqueues the typed prompt.

A REFUSED submission keeps the text. The prompt is the one place in the TUI where the user may have typed a paragraph, and losing it to a full queue or an unavailable provider would be the worst data loss the TUI can inflict.

func (*Model) SwitchView

func (m *Model) SwitchView(view string)

SwitchView moves to the named tab.

func (*Model) TabOwnsFocus added in v1.12.0

func (m *Model) TabOwnsFocus() bool

TabOwnsFocus reports whether Tasks must receive Tab itself. Every input and blocking overlay owns it; passive list/detail/response contexts do not, so an outer deck may intercept Tab there. Standalone Tasks still receives Tab and retains its established "Ask" behavior.

func (*Model) TabStrip

func (m *Model) TabStrip(width int) string

TabStrip renders the tab cells, degrading labels when they do not fit.

Ruby's version drops tabs one at a time from the far end and re-measures at each of five degradation steps. This one degrades the LABELS in three steps (full, compact, minimum) and keeps every tab, because a tab that disappears from the strip is a view the user cannot see exists, and the number keys that jump to it keep working regardless. That is a genuine user-visible difference; it is recorded in the archived migration compatibility decisions.

func (*Model) TaskEditor

func (m *Model) TaskEditor() *TaskEditorSession

TaskEditor is the open editor session, or nil.

func (*Model) ToggleDeferred

func (m *Model) ToggleDeferred()

ToggleDeferred flips whether unavailable work is shown.

func (*Model) ToggleModel

func (m *Model) ToggleModel()

ToggleModel is `M`.

func (*Model) ToggleRejected added in v1.9.0

func (m *Model) ToggleRejected()

ToggleRejected flips whether recently declined proposals are revealed in intake. Hidden by default; the reveal is what makes a mistaken reject recoverable without leaving the Inbox tab.

func (*Model) UndoLast

func (m *Model) UndoLast()

UndoLast and RedoLast are `u` and ctrl-r.

func (*Model) Update

func (m *Model) Update(message tea.Msg) (tea.Model, tea.Cmd)

Update is the whole event surface. It is a plain method on a value the tests construct directly, so every interaction contract below is checked by driving messages, not by scraping a terminal.

func (*Model) View

func (m *Model) View() tea.View

View renders one frame as a Bubble Tea v2 View. Alt screen and mouse mode live on the View (not program options), matching Sidecar so an external v2 host can host this model without translating tea.Msg values.

func (*Model) VisibleSpatialFocusStops added in v1.12.0

func (m *Model) VisibleSpatialFocusStops() []SpatialFocusStop

VisibleSpatialFocusStops reports the list and, when it actually has rendered columns, the detail panel. Geometry comes from the same ScreenLayout sampled by rendering and mouse routing.

func (*Model) YankMarkdown

func (m *Model) YankMarkdown()

YankMarkdown is `Y`: copy the task as a markdown checkbox line with its notes.

func (*Model) YankRef

func (m *Model) YankRef()

YankRef is `y`: copy the stable reference the CLI accepts.

type Opener

type Opener interface {
	// Open launches the URL and reports whether a launcher could be spawned.
	Open(url string) bool
}

Opener launches a URL. It is an INTERFACE, not a function call, because the alternative is a test suite that opens real browser windows.

type Options

type Options struct {
	App     *application.Application
	Paths   config.Paths
	Env     determinism.Env
	Styler  Styler
	Now     func() time.Time
	Session SessionState
	// Opener launches a task's link. A nil one refuses out loud rather than
	// reaching for a platform launcher, which is what keeps a test suite from
	// opening browser windows.
	Opener Opener
	// CopyToClipboard is a test seam for yank actions. Nil uses the platform
	// clipboard command; tests inject a recorder and never touch the real one.
	CopyToClipboard func(string) bool
	// Entries are the provider/model pairs the prompt can be submitted to, and
	// Queue is the coordinator that runs them. Both are injected: a test and
	// the differential supply fakes, and a nil queue refuses the prompt out
	// loud rather than reaching for a real provider.
	Entries []AgentEntry
	Queue   *agentQueue
	// Embedded keeps nested quit commands inside the model: quit latches a
	// request the host reads through QuitRequested rather than terminating.
	// SuppressQuit says the HOST owns the quit affordance, so Tasks drops quit
	// from its own key hint; the request still latches, because a host that
	// suppresses quit is precisely the host that needs to observe it.
	// SuppressFooter drops the ENTIRE footer stack — agent transcript, store-read
	// banner, flash, filter lines, prompt, and key hints — for a host that paints
	// its own. SuppressKeyHints drops ONLY Tasks' ordinary key-hint row, on the
	// same "the host owns the affordance" reading as SuppressQuit; everything
	// else in the stack, the prompt above all, keeps rendering.
	// SuppressViewKeyHints is the same reading applied to the header: Tasks drops
	// the numeric prefixes from its view tab strip, keeping the view names and the
	// active-tab highlight, and keeps acting on 1-6.
	Embedded             bool
	SuppressFooter       bool
	SuppressKeyHints     bool
	SuppressViewKeyHints bool
	SuppressQuit         bool
	// SaveSession overrides standalone persistence for a host namespace.
	SaveSession func(SessionState) error
}

Options builds a Model. Every seam a test needs to pin is here: the clock, the environment, and the styler.

type OverlayBox

type OverlayBox struct {
	Lines []string
	Row   int
	Col   int
	// FocusedContentRow is the row inside Lines carrying the caret, or -1.
	FocusedContentRow int
	// Backdrop dims the frame cells BESIDE the box (the rows it spans) in the
	// modal_backdrop slot. Only the modals that ask for it get it — palettes
	// and quick forms keep their flat surroundings until they opt in.
	Backdrop bool
}

OverlayBox is a popup positioned in the frame.

type PaletteOutcome

type PaletteOutcome struct {
	Kind PickerResultKind
	// Entry is set when Kind is PickerAccepted: the action to run.
	Entry   shortcuts.Entry
	Execute bool
}

PaletteOutcome is what a palette key did.

type PanelView

type PanelView struct {
	Title string
	Lines []string
	Width int
}

PanelView is one frame of panel content.

type PickerOption

type PickerOption struct {
	ID         string
	Label      string
	SearchText []string
	Kind       PickerOptionKind
	// Metadata is the caller's own payload. The action palette hangs the whole
	// shortcut entry here so it can execute what the user picked without
	// re-deriving it from an id.
	Metadata any
}

PickerOption is one choice. A command option (Kind == PickerCommand) is not a selection at all — it runs a mutation over the staged set, which is how "Clear all contexts" lives in the same list as the contexts it clears.

type PickerOptionKind

type PickerOptionKind string

PickerOptionKind separates a selectable choice from a command.

const (
	PickerChoice  PickerOptionKind = "choice"
	PickerCommand PickerOptionKind = "command"
)

The two option kinds.

type PickerResult

type PickerResult struct {
	Kind PickerResultKind
	IDs  []string
}

PickerResult is one outcome.

type PickerResultKind

type PickerResultKind string

PickerResultKind is what one key or click did.

const (
	PickerHandled   PickerResultKind = "handled"
	PickerChanged   PickerResultKind = "changed"
	PickerCancelled PickerResultKind = "cancelled"
	PickerAccepted  PickerResultKind = "accepted"
)

The picker outcomes. Accepted carries the ids the caller should apply.

type PlainStyler

type PlainStyler struct{}

PlainStyler is the boring default: no color, and width measured in runes.

It exists so this package is testable and runnable before term/ lands, and so golden row fixtures are plain text rather than a wall of escape bytes. It is NOT the shipping styler — it counts a wide character as one cell, which is exactly the thing term/ is being written to get right.

func (PlainStyler) Composite added in v1.6.0

func (PlainStyler) Composite(_, text string) string

Composite returns the text unchanged: with nothing painted there is nothing to layer under.

func (PlainStyler) Paint

func (PlainStyler) Paint(_, text string) string

Paint returns the text unchanged.

func (PlainStyler) Truncate

func (PlainStyler) Truncate(text string, width int) string

Truncate cuts to width runes.

func (PlainStyler) Width

func (PlainStyler) Width(text string) int

Width counts runes. See the type comment for why this is a placeholder.

func (PlainStyler) Wrap

func (PlainStyler) Wrap(text string, width int) []string

Wrap folds on spaces, breaking an over-long word rather than overflowing.

type QuickForm

type QuickForm struct {
	Kind QuickFormKind
	// TargetID is the row the form was opened for. A form outliving its target
	// must not act on whatever the selection became.
	TargetID   string
	ReturnMode ReturnMode

	// Success is the effect to run after a successful submit, set by the submit
	// callback itself. Ruby stores it on the UI state; keeping it on the form
	// means closing the form cannot leave a stale callback behind.
	Success func()
	// contains filtered or unexported fields
}

QuickForm is the reusable lifecycle for the TUI's small single-field popups.

The caller supplies domain validation and the mutation; this owns input editing, paste, the error line, rendering and the return mode. The submit callback returns a MESSAGE on failure and "" on success, which is what lets every popup report its own refusal in its own words without the form knowing anything about tasks.

func NewQuickForm

func NewQuickForm(options QuickFormOptions) *QuickForm

NewQuickForm builds one.

func (*QuickForm) Cursor

func (q *QuickForm) Cursor() int

Cursor is the caret offset.

func (*QuickForm) Error

func (q *QuickForm) Error() string

Error is the last refusal message.

func (*QuickForm) HandleKey

func (q *QuickForm) HandleKey(key string) QuickFormResult

HandleKey routes one raw key.

func (*QuickForm) Hint

func (q *QuickForm) Hint(width int) string

Hint resolves the hint against the current input and the cells it may use.

func (*QuickForm) Paste

func (q *QuickForm) Paste(text string) QuickFormResult

Paste inserts pasted text.

func (*QuickForm) Popup

func (q *QuickForm) Popup(styler Styler, maxWidth, maxHeight int) FormRender

Popup renders the form at the given budget.

func (*QuickForm) SetText

func (q *QuickForm) SetText(text string)

SetText replaces the input through the engine, so a host-driven replacement participates in dirty-state rendering instead of mutating a second buffer.

func (*QuickForm) Submit

func (q *QuickForm) Submit() QuickFormResult

Submit runs the caller's mutation.

func (*QuickForm) Text

func (q *QuickForm) Text() string

Text is the current input.

func (*QuickForm) Title

func (q *QuickForm) Title() string

Title is the popup's title.

type QuickFormKind

type QuickFormKind string

QuickFormKind names which quick form is open, so a test and a hit test can both say which popup they mean.

const (
	QuickFormDate           QuickFormKind = "date"
	QuickFormRecurrence     QuickFormKind = "recurrence"
	QuickFormDeferUntil     QuickFormKind = "defer_until"
	QuickFormProjectRename  QuickFormKind = "project_rename"
	QuickFormProjectCapture QuickFormKind = "project_capture"
	QuickFormSectionDates   QuickFormKind = "section_dates"
	// Delegation is deliberately absent: `D` is a multi-field modal
	// (FieldModalDelegate), because a delegation needs three different KINDS of
	// answer and one text field could only carry them as a word grammar.
	QuickFormWorkRef QuickFormKind = "work_ref"
)

The quick forms this build has. The agent prompt is deliberately absent — it belongs to the agent packet.

type QuickFormOptions

type QuickFormOptions struct {
	Kind       QuickFormKind
	Title      string
	Prompt     string
	Hint       string
	HintFunc   func(text string, width int) string
	MinWidth   int
	ReturnMode ReturnMode
	Initial    string
	// Suffix is the fixed gloss shown after the value — the recurrence popup
	// uses it to say what the task repeats on right now.
	Suffix   string
	TargetID string
	// Submit returns "" on success and a user-visible message on refusal.
	Submit func(text string) string
}

QuickFormOptions builds a QuickForm.

type QuickFormResult

type QuickFormResult string

QuickFormResult is what one key did to a quick form.

const (
	QuickFormHandled   QuickFormResult = "handled"
	QuickFormChanged   QuickFormResult = "changed"
	QuickFormCancelled QuickFormResult = "cancelled"
	QuickFormSubmitted QuickFormResult = "submitted"
	QuickFormError     QuickFormResult = "error"
)

The four outcomes.

type ReturnMode

type ReturnMode string

ReturnMode is where an overlay goes when it closes. A palette opened from a modal must return TO that modal, or dismissing it would silently close two things at once.

const (
	ReturnList  ReturnMode = "list"
	ReturnModal ReturnMode = "modal"
)

The two return modes an overlay can carry.

type RightPanel

type RightPanel struct {
	Title    string
	Kind     string
	Identity string
	Lines    []string
	Scroll   int

	FocusedRow    int
	HasFocusedRow bool
}

RightPanel is the persistent panel on the right side — the port of lib/tui/right_panel.rb.

The behavior worth preserving is the scroll rule: replacing content for the SAME identity keeps the reader's place, and moving to another task starts the new content at the top. A refresh caused by an external file write must not throw a reader back to the first line of a long note.

func NewRightPanel

func NewRightPanel(title, kind, identity string, lines []string) *RightPanel

NewRightPanel builds a panel showing content for one identity.

func (*RightPanel) Bare added in v1.6.0

func (p *RightPanel) Bare() bool

Bare reports whether this panel paints its own headings and therefore wants no title bar above it.

Detail content opens on a labelled `TASK ────` rule that already says what the panel is, so a "task" title and a divider above it would be the same sentence twice — and two rows of a short terminal is a real price for it. The suspended-editor panel keeps its chrome: its content is a form, and the title is the only thing that says what the form belongs to.

func (*RightPanel) FocusRow

func (p *RightPanel) FocusRow(row int)

FocusRow asks the next view to reveal a specific content row. The editor packet uses this to keep the focused field on screen.

func (*RightPanel) Replace

func (p *RightPanel) Replace(title, identity string, lines []string) *RightPanel

Replace swaps the content. Scroll resets only when the identity changes.

func (*RightPanel) ScrollHalf

func (p *RightPanel) ScrollHalf(direction, height int)

ScrollHalf moves by half a viewport, at least one line.

func (*RightPanel) ScrollLine

func (p *RightPanel) ScrollLine(delta, height int)

ScrollLine moves by whole lines.

func (*RightPanel) ScrollPage

func (p *RightPanel) ScrollPage(direction, height int)

ScrollPage moves by a whole viewport.

func (*RightPanel) View

func (p *RightPanel) View(styler Styler, height, width int) PanelView

View renders the panel into the given box. The title and divider consume two body rows. A status row appears only when the content overflows, and is included in the returned line budget.

func (*RightPanel) Viewport

func (p *RightPanel) Viewport(height int) int

Viewport is the number of content lines visible at this height.

type Row

type Row struct {
	Text string

	// Item is the task this row acts on, nil for headers, blanks, and project
	// header rows.
	Item *store.Item
	// Node is the tree node behind a tree-mode task row, nil in flat mode.
	Node *taskquery.Node
	// Project is the rolled-up view behind a selectable Projects header row.
	Project *taskquery.ProjectView

	// MarkerSpan is the [begin, end) cell range of the collapse marker, for
	// mouse hit testing. Zero-width when the row carries no marker.
	MarkerBegin int
	MarkerEnd   int

	// ContextExcept is the one `@context` this row's context column suppresses:
	// the name of the group the row already sits under. The Next view groups BY
	// context, so repeating the group's own name on every row under it says
	// nothing — while the row's OTHER contexts are exactly what that grouping
	// hides, and they stay. Empty on every view that does not group by context.
	ContextExcept string

	// Chrome marks a row that is structure rather than content: a section rule
	// or the blank between two blocks. Chrome is painted FLUSH to the pane's
	// left edge, where a content row's cursor field sits, so a rule's label
	// starts on the same column the cursor does. An empty-state placeholder is
	// NOT chrome — it occupies a row's place and wears a row's indent.
	Chrome bool
}

Row is one painted line of the list — the port of Tui::Views::Row.

A row is SELECTABLE (actions apply to it) when it carries an item or a project; a row with neither is a header or a blank. In tree mode a task row also carries its tree node so the model can answer hierarchy questions (collapse, expand, jump to parent) without re-deriving them.

Rows never name a color. Builders paint through semantic slots so the active theme decides the final look, and the renderer highlights the selected row by reversing its text.

func BuildRows

func BuildRows(request BuildRequest) []Row

BuildRows is the single entry point: `Views.rows`.

UseTree false is the flat path a `/` search always takes (its result shape is what filtering expects). UseTree true is the outliner, which nests each anchor's visible subtree beneath it with indent and markers.

func (Row) HasMarker

func (r Row) HasMarker() bool

HasMarker reports whether this row has a clickable collapse marker.

func (Row) ID

func (r Row) ID() string

ID is the durable identity selection follows across re-renders: a task id or a section id. Both live in the same 8-hex space, so one field suffices.

func (Row) Selectable

func (r Row) Selectable() bool

Selectable reports whether the cursor may land on this row.

type RuntimeOptions added in v1.1.0

type RuntimeOptions struct {
	Paths   config.Paths
	Env     determinism.Env
	Session SessionState
	Styler  Styler

	Embedded             bool
	SuppressFooter       bool
	SuppressKeyHints     bool
	SuppressViewKeyHints bool
	SuppressQuit         bool
	SaveSession          func(SessionState) error
}

RuntimeOptions configures the shared shipping constructor used by both the standalone executable and public embedding adapter.

type ScreenLayout

type ScreenLayout struct {
	Width  int
	Height int
	Footer []string

	BodyHeight int
	BodyWidth  int

	ListWidth         int
	PanelWidth        int
	PanelContentWidth int
	PanelMode         string
	RequestedMode     string
	PanelOffset       int

	Selected          int
	HasSelection      bool
	ViewportOffset    int
	SelectedScreenRow int

	EditContentHeight int
	Editing           bool
}

ScreenLayout is pure geometry for ONE sampled terminal frame — the port of lib/tui/screen_layout.rb.

Ruby introduced it so a resize could not mix dimensions from two winsize reads. Bubble Tea removes that hazard (a WindowSizeMsg is one coherent value), but the type earns its keep for the other reason: rendering, panel placement, selection coordinates and mouse hit testing all have to agree about where row 2 is, and the only way to guarantee that is to compute it once.

func NewScreenLayout

func NewScreenLayout(styler Styler, request LayoutRequest) ScreenLayout

NewScreenLayout computes one frame's geometry.

func (ScreenLayout) BodyRows

func (l ScreenLayout) BodyRows() (int, int)

BodyRows is [begin, end) of the list body.

func (ScreenLayout) ContentBreakpoint

func (l ScreenLayout) ContentBreakpoint() string

ContentBreakpoint is the responsive-width decision the editor renders against.

func (ScreenLayout) EditablePanel

func (l ScreenLayout) EditablePanel() bool

EditablePanel reports whether the panel is large enough to host the editor. The editor packet owns what "editing" means; this is the geometry half of the contract, and it is here because the width ladder is here.

func (ScreenLayout) FooterRows

func (l ScreenLayout) FooterRows() (int, int)

FooterRows is [begin, end) of the footer.

func (ScreenLayout) FooterSize

func (l ScreenLayout) FooterSize() int

FooterSize is the number of footer rows this frame reserved.

func (ScreenLayout) HasPanel

func (l ScreenLayout) HasPanel() bool

HasPanel reports whether the right panel occupies any columns.

func (ScreenLayout) HeaderRow

func (l ScreenLayout) HeaderRow() int

HeaderRow is the row the tab strip paints on.

func (ScreenLayout) ListCols

func (l ScreenLayout) ListCols() (int, int)

ListCols is [begin, end) of the list columns.

func (ScreenLayout) PanelCols

func (l ScreenLayout) PanelCols() (int, int)

PanelCols is [begin, end) of the panel columns, empty with no panel.

func (ScreenLayout) PanelDividerCol

func (l ScreenLayout) PanelDividerCol() int

PanelDividerCol is the column the split rule occupies, or -1 with no panel.

func (ScreenLayout) VisibleRows

func (l ScreenLayout) VisibleRows(rows []Row) []Row

VisibleRows is the slice of rows this frame paints.

type ScreenRect added in v1.12.0

type ScreenRect struct {
	X, Y          int
	Width, Height int
}

ScreenRect is one half-open rectangle in the rendered terminal frame.

type ScrollThumb added in v1.14.0

type ScrollThumb struct {
	Pos  int  // first track row of the thumb.
	Size int  // track rows the thumb spans; always >= 1 when Has is set.
	Has  bool // false when all content fits and no thumb should be drawn.
}

ScrollThumb is a scrollbar thumb's placement within its track.

func ThumbLocFor added in v1.14.0

func ThumbLocFor(totalItems, scrollOffset, visibleItems, trackHeight int) ScrollThumb

ThumbLocFor computes proportional thumb placement from list geometry: size is the visible fraction of the track with a floor of one row, position tracks the scroll offset across the remaining travel. Has is false when totalItems does not exceed visibleItems. Adapted from sidecar's internal/scroll/thumb.go.

type Section added in v1.6.0

type Section struct {
	Label     string
	Slot      string
	Right     string
	RightSlot string
	Rows      []Row
	// Empty is the row painted when the block has nothing in it. A nil Empty
	// drops the whole block, rule and all: an empty heading costs two lines to
	// say nothing.
	Empty *Row
}

Section is one labelled block of a view: the rule, then its rows.

Right is the badge on the shared right edge. Left empty it becomes the count of selectable rows in the block, which is what it almost always is — spelling that once here is why no view can drift into counting its own rows wrong.

type SelectionMode

type SelectionMode string

SelectionMode is single- or multiple-choice.

const (
	SelectSingle   SelectionMode = "single"
	SelectMultiple SelectionMode = "multiple"
)

The two selection modes.

type SessionState

type SessionState struct {
	View           string   `json:"view,omitempty"`
	Collapsed      []string `json:"collapsed,omitempty"`
	PanelMode      string   `json:"panel_mode,omitempty"`
	PanelOffset    int      `json:"panel_offset,omitempty"`
	ContextFilters []string `json:"context_filters,omitempty"`

	// ContextFilter is the retired singular spelling. It is read so an existing
	// state file keeps working, and never written.
	ContextFilter string `json:"context_filter,omitempty"`
}

SessionState is the small bit of UI preference that survives a restart: the active view, the collapsed set, the panel geometry, and the context filters. It is the port of lib/tui/session.rb plus UiState's restore/serialize halves.

It is deliberately dumb. This is UI preference, not task data — one file per user, and losing it costs nothing but a default. EVERY read tolerates a missing, corrupt, or foreign-version file by returning the zero value: session state must never be able to keep the TUI from starting.

func LoadEmbeddedSession added in v1.1.0

func LoadEmbeddedSession(env determinism.Env, namespace string) SessionState

LoadEmbeddedSession reads a host-specific embedded session.

func LoadSession

func LoadSession(env determinism.Env) SessionState

LoadSession reads the saved state, or the zero value when there is none to be had.

type SpatialFocus added in v1.12.0

type SpatialFocus string

SpatialFocus names the stable, spatially arranged regions an embedding host may include in its own focus ring. It is deliberately separate from FocusContext: list/detail describe where focus sits in the rendered frame, while prompt, editor, picker, and modal contexts describe who owns keys.

const (
	SpatialFocusList   SpatialFocus = "list"
	SpatialFocusDetail SpatialFocus = "detail"
)

type SpatialFocusStop added in v1.12.0

type SpatialFocusStop struct {
	ID   SpatialFocus
	Rect ScreenRect
}

SpatialFocusStop is one visible focus destination and its exact rendered geometry. IDs are stable; order is the visual reading order.

type StatusLevel added in v1.14.0

type StatusLevel int

StatusLevel says what kind of news a status line carries.

const (
	StatusNone StatusLevel = iota
	StatusError
	// StatusWarning is the armed destructive-action state: loud enough to
	// demand attention, but not claiming something already failed.
	StatusWarning
)

type Styler

type Styler interface {
	// Paint renders text in the named slot.
	Paint(slot, text string) string
	// Composite renders ALREADY-PAINTED text underneath the named slot,
	// re-opening the slot after every reset the text carries so the inner
	// styling layers over it instead of clearing it.
	//
	// This is what a selected row needs and Paint cannot give it. Paint wraps:
	// it opens the slot, and the first field inside the row that closes its own
	// styling with a reset takes the selection down with it — so a row with a
	// coloured priority letter highlights the one cell before that letter and
	// nothing after. Composite is the same operation the frame renderer uses,
	// promoted to the seam because the shell is where selection is decided.
	Composite(slot, text string) string
	// Width is the DISPLAY width of text in terminal cells: escape sequences
	// count zero and a wide character counts two.
	Width(text string) int
	// Truncate cuts text to at most width cells, preserving styling and never
	// splitting a wide character across the boundary.
	Truncate(text string, width int) string
	// Wrap folds text to lines of at most width cells.
	Wrap(text string, width int) []string
}

Styler is the ONLY thing this package needs from the rendering half of the TUI (`internal/tui/term`). It is deliberately tiny: four operations, no theme type, no color model, no escape-sequence vocabulary.

Rows and detail lines name a semantic SLOT (":title", ":muted", ":due_soon") exactly as the Ruby builders do; the styler decides what a slot looks like, including deciding that it looks like nothing at all under NO_COLOR.

Width, Truncate and Wrap are separate from Paint because a painted string contains bytes that occupy no cells, and every layout decision in this package is made in CELLS. A styler that paints must measure.

type SystemOpener

type SystemOpener struct {
	// Env is the environment the override is read from. A nil Env reads the
	// process environment.
	Env determinism.Env
}

SystemOpener launches a URL in the user's browser — the Go port of Tasks::Opener's behavior. In Ruby that module is shared by `tasks open` and the TUI's `o`; on this side it is TUI-OWNED, because the Go `open` command resolves its launcher itself. What is shared is the contract, not the code.

TASKS_OPENER overrides the platform launcher and is SHELL-SPLIT, so `TASKS_OPENER="open -a Safari"` works. That override is also how a test observes an open without a browser appearing, which is why it is honoured before the platform default rather than after it.

func (SystemOpener) Command

func (o SystemOpener) Command() ([]string, bool)

Command is the launcher argv without the URL, and whether there is one to run at all.

A RAW non-empty override is AUTHORITATIVE: if the user set TASKS_OPENER, that is the launcher, and a malformed or empty-splitting value means there is no launcher — never a quiet fall back to the platform default. Falling back would silently open a browser the user had explicitly configured away from, which is the one outcome an override exists to prevent.

This is exactly what Ruby does, by a different route: `Shellwords.split` raises on an unmatched quote or NUL and `Opener.open_url` rescues ArgumentError into false; a whitespace-only or quoted-empty override splits to no usable launcher and the spawn fails. Both arrive at "no open, and say so".

func (SystemOpener) Open

func (o SystemOpener) Open(url string) bool

Open launches the URL detached and reports whether the launcher could be spawned at all.

Output is DISCARDED: a TUI must not have a browser's stderr scribbled over it. And any spawn failure — a missing launcher, a non-executable TASKS_OPENER — returns false rather than propagating, because a bad opener must not take the interface down on a keystroke.

type Tab

type Tab struct {
	Label   string
	Compact string
	Minimum string

	Key string
}

Tab is one entry of the header strip, in the three sizes the strip degrades through as the terminal narrows.

The names carry no jump key. The keys 1-6 still work, and they are advertised once — in the footer's `1-6 views` hint — rather than stamped onto all six tabs. A host that has taken the number row for itself (EmbeddedOptions.SuppressViewKeyHints) drops that one hint; the keys keep working either way, and the strip is unaffected because there is nothing in it to suppress.

type TaskEditForm

type TaskEditForm struct {
	// contains filtered or unexported fields
}

TaskEditForm is the task-domain policy adapter around the neutral form engine. It owns field order, task-specific normalization and options, and the per-field expectations a patch is guarded by. The session owns effects.

func NewTaskEditForm

func NewTaskEditForm(options TaskEditFormOptions) (*TaskEditForm, error)

NewTaskEditForm builds the editor over one snapshot.

func (*TaskEditForm) AcceptCommit

func (t *TaskEditForm) AcceptCommit(fresh *EditSnapshot, token int) (termform.Transition, error)

AcceptCommit resolves a pending save against a fresh read.

func (*TaskEditForm) ExpectedFor

func (t *TaskEditForm) ExpectedFor(field string) string

ExpectedFor is the baseline a patch on one field must match.

func (*TaskEditForm) Form

func (t *TaskEditForm) Form() *termform.Form

Form is the underlying engine.

func (*TaskEditForm) PatchField

func (t *TaskEditForm) PatchField(field string) store.PatchField

PatchField is the store field an editor field patches.

func (*TaskEditForm) ReadOnly

func (t *TaskEditForm) ReadOnly() (id, closed string)

ReadOnly is the pair of facts the editor shows but cannot change.

func (*TaskEditForm) RefreshSnapshot

func (t *TaskEditForm) RefreshSnapshot(fresh *EditSnapshot) error

RefreshSnapshot adopts a fresh read WITHOUT replacing any dirty buffer or its original expectation.

func (*TaskEditForm) RejectCommit

func (t *TaskEditForm) RejectCommit(fieldErrors map[string][]string, message string, token int) termform.Transition

RejectCommit resolves a pending save with a refusal.

func (*TaskEditForm) ReloadField

func (t *TaskEditForm) ReloadField(field string, fresh *EditSnapshot) error

ReloadField discards one local buffer and adopts the fresh persisted value.

func (*TaskEditForm) RevertField

func (t *TaskEditForm) RevertField(field string)

RevertField throws away one field's unsaved edit.

func (*TaskEditForm) SemanticValue

func (t *TaskEditForm) SemanticValue(field string, value any) (text string, typed *store.PatchValue)

SemanticValue converts a form value into the exact value the store's patch for that field owns.

Two spellings come back because the application facade carries both: a string for the fields whose value IS a string (with "" meaning "clear this" for the clearable ones), and a typed store.PatchValue for the three whose value is not — `deferred` is a bool, `contexts` and `tags` are ordered lists. Every field the editor SHOWS goes through one or the other; none refuses.

func (*TaskEditForm) Snapshot

func (t *TaskEditForm) Snapshot() *EditSnapshot

Snapshot is the read the form's baselines came from.

func (*TaskEditForm) TargetID

func (t *TaskEditForm) TargetID() string

TargetID is the task being edited.

type TaskEditFormOptions

type TaskEditFormOptions struct {
	Snapshot       *EditSnapshot
	Today          func() temporal.Date
	Context        temporal.Context
	ContextOptions func() []string
	TagOptions     func() []string
	Focus          string
}

TaskEditFormOptions builds one.

type TaskEditorOptions

type TaskEditorOptions struct {
	App       *application.Application
	Read      func() *application.ReadModel
	Operation func() *application.OperationContext
	Today     func() temporal.Date
	Context   temporal.Context
	TargetID  string
	Focus     string
	// ContextOptions and TagOptions are the completions the two token fields
	// offer.
	ContextOptions func() []string
	TagOptions     func() []string
}

TaskEditorOptions builds a session.

type TaskEditorSession

type TaskEditorSession struct {
	// contains filtered or unexported fields
}

TaskEditorSession coordinates one durable task-edit pass: it translates form transitions into application-owned patches, and holds every piece of recoverable local state while it does.

The design rule throughout is that NOTHING the user typed is ever lost by a refusal. A rejected save keeps the buffer; a conflict keeps the buffer AND offers to copy it; escape asks twice before discarding a field.

func NewTaskEditorSession

func NewTaskEditorSession(options TaskEditorOptions) (*TaskEditorSession, error)

NewTaskEditorSession opens an editor over one task.

func (*TaskEditorSession) CancelConfirmation

func (s *TaskEditorSession) CancelConfirmation() EditorOutcome

CancelConfirmation declines a pending consequence, keeping the local value.

func (*TaskEditorSession) Confirm

func (s *TaskEditorSession) Confirm() EditorOutcome

Confirm accepts a pending consequence and performs the write.

func (*TaskEditorSession) Conflict

func (s *TaskEditorSession) Conflict() *EditorConflict

func (*TaskEditorSession) CopyValue

func (s *TaskEditorSession) CopyValue() any

CopyValue is the value a missing-task editor still holds for the user to copy — the whole reason a vanished task does not simply close the editor.

func (*TaskEditorSession) Dirty

func (s *TaskEditorSession) Dirty(field string) bool

Dirty reports unsaved edits, in the whole form or in one field.

func (*TaskEditorSession) EditForm

func (s *TaskEditorSession) EditForm() *TaskEditForm

func (*TaskEditorSession) Finish

func (s *TaskEditorSession) Finish() EditorOutcome

Finish leaves the editor: immediately when the focused field is clean, and only after that field is accepted when it is not. A refusal always leaves the editor open and recoverable.

func (*TaskEditorSession) FocusedKey

func (s *TaskEditorSession) FocusedKey() string

FocusedKey is the field the caret is in.

func (*TaskEditorSession) Form

func (s *TaskEditorSession) Form() *termform.Form

Form is the underlying engine, or nil for a missing task.

func (*TaskEditorSession) HandleKey

func (s *TaskEditorSession) HandleKey(key string) EditorOutcome

HandleKey routes one raw key through the editor.

func (*TaskEditorSession) HandleQuitConfirmation

func (s *TaskEditorSession) HandleQuitConfirmation(key string) EditorOutcome

HandleQuitConfirmation answers the quit prompt.

func (*TaskEditorSession) KeepForCopy

func (s *TaskEditorSession) KeepForCopy() EditorOutcome

KeepForCopy preserves the local value as an explicit copy payload. The conflict stays active until a reload, so this can never become an overwrite.

func (*TaskEditorSession) Missing

func (s *TaskEditorSession) Missing() bool

func (*TaskEditorSession) Paste

func (s *TaskEditorSession) Paste(text string) EditorOutcome

Paste inserts pasted text into the focused field.

func (*TaskEditorSession) PendingConfirmation

func (s *TaskEditorSession) PendingConfirmation() *EditorConfirmationPrompt

PendingConfirmation and Conflict expose the two blocking states.

func (*TaskEditorSession) PendingQuit

func (s *TaskEditorSession) PendingQuit() bool

PendingQuit reports an armed quit confirmation.

func (*TaskEditorSession) PendingRevert

func (s *TaskEditorSession) PendingRevert() string

PendingRevert is the field an Escape has armed for discard.

func (*TaskEditorSession) Refresh

func (s *TaskEditorSession) Refresh() EditorOutcome

Refresh adopts a fresh read. Dirty buffers keep both their text and the expectation their eventual patch will be compared against.

func (*TaskEditorSession) ReloadConflict

func (s *TaskEditorSession) ReloadConflict() EditorOutcome

ReloadConflict discards the conflicting local buffer and adopts the value that actually landed.

func (*TaskEditorSession) RenderModel

func (s *TaskEditorSession) RenderModel() termform.RenderModel

RenderModel is what the panel paints.

func (*TaskEditorSession) RequestQuit

func (s *TaskEditorSession) RequestQuit() EditorOutcome

RequestQuit asks whether an unsaved draft may be discarded. The DRAFT owns this protection so the same guard follows the editor whether it is visible or suspended by a resize.

func (*TaskEditorSession) Save

func (s *TaskEditorSession) Save() EditorOutcome

Save persists the focused field in place, keeping focus on it.

func (*TaskEditorSession) Snapshot

func (s *TaskEditorSession) Snapshot() *EditSnapshot

func (*TaskEditorSession) Suspend

func (s *TaskEditorSession) Suspend() EditorOutcome

Suspend hides the editor without losing it. Every buffer and durable baseline survives; the transient one-key prompts are DISARMED, because a hidden editor must never retain a destructive action a read-mode key could accept.

func (*TaskEditorSession) TargetID

func (s *TaskEditorSession) TargetID() string

TargetID, EditForm, Snapshot and the predicates are the read surface.

type TemporalControl

type TemporalControl struct {
	Row        temporalRow
	Mode       temporalMode
	ZoneSearch *string
	Lines      []string
}

TemporalControl is the control as the renderer sees it.

type TemporalInput

type TemporalInput struct {
	*termform.DateInput
	// contains filtered or unexported fields
}

TemporalInput is a date field that also opens the structured control.

It embeds the neutral DateInput so the typed path, the parse errors and the calendar are unchanged; what it adds is a second overlay that owns the keyboard while it is open.

func NewTemporalInput

func NewTemporalInput(base termform.Base, hooks termform.DateHooks, today func() temporal.Date,
	suggestions []string, context temporal.Context) *TemporalInput

NewTemporalInput builds one.

func (*TemporalInput) CalendarDate

func (t *TemporalInput) CalendarDate() *temporal.Date

CalendarDate is the day-picker's highlighted day, or nil.

func (*TemporalInput) ControlLines

func (t *TemporalInput) ControlLines(width int) []string

ControlLines renders the control at a width.

func (*TemporalInput) ControlOpen

func (t *TemporalInput) ControlOpen() bool

ControlOpen reports the structured control specifically.

func (*TemporalInput) CursorFor

func (t *TemporalInput) CursorFor(value any, context termform.Context) *int

CursorFor hides the text caret while either overlay owns the keyboard.

func (*TemporalInput) HandleEvent

func (t *TemporalInput) HandleEvent(event termform.Event, value any, context termform.Context) *termform.Result

HandleEvent routes one event: the control first when it is open, then the base field's typed and calendar behavior.

func (*TemporalInput) MetadataFor

func (t *TemporalInput) MetadataFor(value any, context termform.Context) map[string]any

MetadataFor publishes the control for the form renderer.

func (*TemporalInput) PickerOpen

func (t *TemporalInput) PickerOpen() bool

PickerOpen reports either overlay: the structured control or the calendar the base field opens.

func (*TemporalInput) Row

func (t *TemporalInput) Row() temporalRow

Row is the highlighted row.

func (*TemporalInput) Value

func (t *TemporalInput) Value() *temporal.Value

Value is the control's working value.

func (*TemporalInput) ZoneSearch

func (t *TemporalInput) ZoneSearch() *string

ZoneSearch is the live zone query, or nil when the search is not open.

type ViewQuery

type ViewQuery struct {
	View           string
	Queries        *taskquery.Queries
	UrgentDays     int
	ShowDeferred   bool
	ContextFilters []string
}

ViewQuery is the canonical semantic query for both the flat and the tree row builders — the port of Tui::Views::Query.

It owns per-view eligibility, classification and grouping, and item ordering. Tree builders only decide which matching nodes become anchors and then render their descendants; they never re-decide what a view means. That split is what keeps the Agenda tab and `tasks agenda` from drifting apart.

func NewViewQuery

func NewViewQuery(view string, queries *taskquery.Queries, urgentDays int, showDeferred bool,
	contextFilters []string) ViewQuery

NewViewQuery builds the query for one view.

func (ViewQuery) ContextMatch

func (q ViewQuery) ContextMatch(item store.Item) bool

ContextMatch is true when no context filter is active, or the item carries any selected context. Contexts are one OR facet; the view and text predicates compose by AND.

func (ViewQuery) Eligible

func (q ViewQuery) Eligible(item store.Item) bool

Eligible is view-only eligibility: the per-view state/date rule, and then availability.

The active context filter is deliberately NOT folded in here. Agenda anchors a root when ANY subtree item is eligible, and an undated @work parent whose only dates sit on untagged children must keep that thread. Context is a separate predicate; Matching is the conjunction.

The two conjuncts are ordered cheap-first on purpose: the view rule reads fields already on the Item, while the availability test walks task ancestors.

func (ViewQuery) GroupItemsInOrder added in v1.15.0

func (q ViewQuery) GroupItemsInOrder(items []store.Item) []Group

GroupItemsInOrder buckets items by GroupKeys, PRESERVING the order they were given inside each bucket, and returns the buckets in the view's group order.

It is the approvals queue's path: that list is already ranked by the core's shared triage order, and re-sorting a bucket by the view's own key would throw that ranking away. Eligibility is the caller's — the queue's rows are PROPOSED and no view rule admits them.

func (ViewQuery) GroupKeys

func (q ViewQuery) GroupKeys(item store.Item) []string

GroupKeys is the group or groups an item belongs to. A task with several contexts appears once per context in the Next view — which is exactly why selection has to follow an id AND an occurrence, not an id alone.

func (ViewQuery) GroupedNodes

func (q ViewQuery) GroupedNodes(nodes []*taskquery.Node) map[string][]*taskquery.Node

GroupedNodes buckets nodes by GroupKeys and sorts each bucket.

func (ViewQuery) Matching

func (q ViewQuery) Matching(item store.Item) bool

Matching is the composite the filtered views select and anchor on.

func (ViewQuery) Select

func (q ViewQuery) Select(items []store.Item) []store.Item

Select keeps the matching items, in the order given.

func (ViewQuery) SelectNodes

func (q ViewQuery) SelectNodes(nodes []*taskquery.Node) []*taskquery.Node

SelectNodes and SortNodes are the tree-mode twins: the same policy applied to nodes through their items.

func (ViewQuery) Sort

func (q ViewQuery) Sort(items []store.Item) []store.Item

Sort orders items by the view's key. STABLE, deliberately: Ruby's sort_by is not, and Wave 1 already had to fix one list whose tie order was whatever introsort left behind. A list that permutes under an unrelated edit is how a user completes the wrong row.

func (ViewQuery) SortNodes

func (q ViewQuery) SortNodes(nodes []*taskquery.Node) []*taskquery.Node

SortNodes orders nodes by their items' view key, stably.

func (ViewQuery) SortedGroups

func (q ViewQuery) SortedGroups(groups map[string][]*taskquery.Node) []Group

SortedGroups orders the buckets. Most views order by key text; Projects orders by the soonest date anywhere in the bucket, then by key, and Inbox borrows that same sequence outright — see orderGroups.

func (ViewQuery) ViewRule

func (q ViewQuery) ViewRule(item store.Item) bool

ViewRule is the per-view state and date test, availability aside.

Directories

Path Synopsis
Package term is the seam between the TUI shell and the terminal primitives under term/.
Package term is the seam between the TUI shell and the terminal primitives under term/.
agent
Package agent is the serial coordinator for autonomous TUI agent requests and the presentation of their transcripts.
Package agent is the serial coordinator for autonomous TUI agent requests and the presentation of their transcripts.
ansi
Package ansi holds the SGR-aware, width-aware string helpers.
Package ansi holds the SGR-aware, width-aware string helpers.
border
Package border is the single owner of box-drawing chrome: rounded corners plus an angled truecolor gradient swept across a container's border cells.
Package border is the single owner of box-drawing chrome: rounded corners plus an angled truecolor gradient swept across a container's border cells.
charwidth
Package charwidth answers the terminal display width of Unicode codepoints and grapheme clusters.
Package charwidth answers the terminal display width of Unicode codepoints and grapheme clusters.
clipboard
Package clipboard writes to the system clipboard via whatever tool the platform has, with no third-party dependency.
Package clipboard writes to the system clipboard via whatever tool the platform has, with no third-party dependency.
frame
Package frame is a pure frame builder: given content, it returns one string per terminal row, each exactly `width` visible cells wide.
Package frame is a pure frame builder: given content, it returns one string per terminal row, each exactly `width` visible cells wide.
hitmap
Package hitmap is pure geometry: it maps a screen (row, col) to a Hit zone using the rectangles a layout publishes.
Package hitmap is pure geometry: it maps a screen (row, col) to a Hit zone using the rectangles a layout publishes.
input
Package input holds the terminal input primitives: the raw key sequences the TUI recognizes, a raw-bytes-to-semantic-event key map, and the grapheme-aware single-line/multi-line text editor used by the prompt and by form fields.
Package input holds the terminal input primitives: the raw key sequences the TUI recognizes, a raw-bytes-to-semantic-event key map, and the grapheme-aware single-line/multi-line text editor used by the prompt and by form fields.
layout
Package layout is pure geometry for one sampled terminal frame.
Package layout is pure geometry for one sampled terminal frame.
mouse
Package mouse is a pure SGR mouse-report decoder plus the (mode, zone, button, action) → intent table.
Package mouse is a pure SGR mouse-report decoder plus the (mode, zone, button, action) → intent table.
shortcuts
Package shortcuts is the declarative registry for every keyboard action shown in help.
Package shortcuts is the declarative registry for every keyboard action shown in help.
theme
Package theme is the semantic color layer.
Package theme is the semantic color layer.
Package termform is the persistence-neutral form engine the TUI's editor and popups are built from — the Go port of Ruby's lib/term_form/.
Package termform is the persistence-neutral form engine the TUI's editor and popups are built from — the Go port of Ruby's lib/term_form/.

Jump to

Keyboard shortcuts

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