Tenon TUI Cookbook
A practical guide to building pure, deterministic terminal
interfaces with Tenon's TUI plugin suite. For package-level
contracts and limits, follow the links to each plugin's
DOCS.md instead of treating this cookbook as a
duplicate spec.
Start from a working app by copying examples/tui/template/,
or see the end-to-end inline + headless capstone in examples/tui/assistant/.
1. Mental model
Every Tenon TUI splits cleanly into a pure
application (capabilities = []) and an
effectful host driver (such as examples/tui/driver/lib.tn):
- Your application implements
tui.runtime.App:update(self, event: Event) -> Step<Self>returns the next immutable state and avec<Effect>of requested actions.view(self, size: Size) -> Screenreturns an immutableFrameof styledStriprows, optionalCursor,Modes,Hitregions, focus order, and optionalModal.
- The runtime drives
Appdeterministically throughtui.runtime.tick<A: App>(Runtime<A>, Input) -> Tick<A>after initializing withstart(app, size, caps)(tests/scenarios) orstart_probing(app, size, now, term, colorterm)(live terminals). Inputhas four variants:Bytes(bytes, now),Feed(bytes, now),Resize(Size, now), andClock(now). Every input delivers a nonvisualEvent.Time(now)before its other events;Event.Tick(now)and lone-ESC flushing (30 ms) occur only onInput.Clock.Tick<A>gives the host exact outputout: bytes,wait_ms: i64(-1means idle with zero wakeups),requests: vec<Request>for the host to authorize, andquit: bool.- Effects are data, never I/O. Pure
Appcode never touches/dev/tty, files, clocks, or sockets.Effectvalues (Quit,Timer,Frame,Run,Send,Focus,Capture,Release,Request) are interpreted by the runtime or explicitly authorized by the host.
Design ADRs: 0220 Strips and canvas · 0221 Native terminal boundary · 0222 Unix feed · 0223 Commands and messages · 0224 FFI cleanup · 0225 Presented metadata and scroll diff · 0226 Capability witness · 0227 Capability delivery before layout · 0285 TUI agent surface (M24) · 0292 Application Actions API · 0293 Actions API v1.1 and derive Actions · 0325 Explicit state machines.
Core reference: plugins/tui/DOCS.md.
2. Choosing a structure
| Structure | When to use it | Key entry points |
|---|---|---|
Hand-composed App |
Custom geometry, split panes
(tui_layout.flex.flex), modals, or full control over
layers and focus. |
tui.runtime.App,
tui.compose.compose, tui_layout/DOCS.md |
derive Shell |
Vertically stacked independent panels implementing
tui_shell.plugin.Plugin with automatic per-slot
caching, chord routing, and fault isolation
(error_placeholder,
shell_screen_with_faults). |
tui_shell.lib.Shell,
tui_shell.plugin.Plugin, tui_shell/DOCS.md |
Inline viewport (tui_inline) |
Painting a bounded Block into a bottom-anchored
sub-rectangle without alternate screen and committing finished
turns into native scrollback. |
tui_inline.lib.viewport_policy,
paint, grow, reanchor,
commit, invalidate,
rebase_policy, tui_inline/DOCS.md |
Use tui_forms (or the cohesive
std_tui
edition = "2026" facade, which bundles
tui_forms with tui.a11y accessibility
tree integration) for schema-driven modal forms and structured
configuration prompts (std_tui/DOCS.md,
tui_forms/DOCS.md).
Legacy tui_form (derive TuiForm) remains
preserved for backward compatibility (tui_form/DOCS.md).
3. Width policy
(Caps.cluster)
Terminals disagree on whether grapheme clusters such as ZWJ
emoji (👩💻) occupy 2 cells
(cluster = true) or the sum of their scalar widths
(cluster = false).
- Capture
Event.Capabilities(caps)in app state (cluster: bool).startqueues an initial snapshot before input, andstart_probingdelivers the negotiated snapshot before rendering when the probe freezes (DA reply or 150 ms). Intui_shell, plugins that render width-sensitive content must returntrueforEvent.Capabilitiesinwants. - Pass
clusterto every*_policyhelper before clipping or geometry:- Core:
tui.types.span_policy,tui.text.line_policy,width_policy,tui.canvas.canvas_policy,tui.unicode.clusters_policy,display_width_policy. - Widgets (
tui_widgets/DOCS.md):text_view_policy,list_view_policy,input_view_policy,input_cursor_policy,border_policy,tabs_view_policy,spinner_view_policy,spinner_view_elapsed_policy,progress_view_policy,progress_bar_policy,progress_labeled_policy,progress_indeterminate_policy,progress_indeterminate_bar_policy,table_view_policy,table_render_policy. - Markdown / Highlight / Inline / Editor / Complete:
tui_md.lib.markdown_policy,resize_policy,tui_highlightview_policy,tui_inline.lib.viewport_policy,rebase_policy,tui_editor.view.editor_view_policy,editor_height_policy,tui_complete.popup.popup_view_policy,tui_complete.palette.palette_view_policy.
- Core:
- Never rely on runtime normalization to fix clipped
text. If a widget truncates a string using legacy scalar
widths (
cluster = false), the dropped suffix is already gone beforetui.runtimenormalizes the finalScreen. See ADR-0227.
4. Input and keys
- Kitty refinement: Call
tui_keys.lib.normalize_event(event)(ortui_keys.lib.kitty(key)) at the top ofupdate. It refines raw CSI-u keys, preserves routed focusTargets, and returnsnonefor key-release reports so apps do not double-fire actions. - Chords and bindings: Keep
Keys(tui_keys.lib.keys()) andnow: i64(updated fromEvent.Time(now)) in state. Callresolve(state.keys, key, bindings, state.now)to getResolved { state, commands, consumed }. Pending multi-key chords expire after 1000 ms; scheduleEffect.Timer(id, res.state.due - now)whenres.state.due >= 0so idle runtimes still wake on expiry. - Defaults and dispatch:
tui_keys.lib.defaults()providesctrl+c(quit),ctrl+p(palette), andpageup/pagedown(scroll). Usetui_keys.lib.dispatch(state, commands, handlers)to fold commands through amap<str, fn(S, str) -> S>. - Routing order (
tui_shell): Focused target -> owning plugin (with target cleared) -> that layer's keymap -> global keymap. The first state change or nonemptyeffectsconsumes the key.tui_shell.plugin.keymap_timer()reserves timer ID-9223372036854775807for chord expiry; use distinct IDs for app timers.
Reference: plugins/tui_keys/DOCS.md.
5. Mouse, hits, capture and modals
- Hits and local coordinates: Widgets emit
Hit { rect, target, cursor }withTarget { slot, id }.tui.compose.compose(size, layers)clips layers byzorder, removes occluded hits, preserves each target's local origin, and buildsScreen.focus_orderfrom the topmost layer. Mouse events arrive withtarget: option<Target>andlocal_x/local_yrelative to the target's unclipped origin. - Capture and selection: Emit
Effect.Capture(target)on press to keep receiving pointer moves outside the hit rect, andEffect.Releaseon release. The runtime also releases capture on button-up, terminal focus loss, or target removal. For text drag-selection, usetui_selection.lib(empty,press,move,release,cancel,selected,highlight,copy) and route focus loss or cancellation tocancel/release(tui_selection/DOCS.md). - Modals: Set
Layer { ..., modal: true }at a higherzthan background layers. Focus traversal stays inside the modal; a modal without a focused interactive target consumes keys instead of leaking them to background handlers, whileEvent.FeedandEvent.Commandremain able to dismiss it.
6. Requests the host must approve
Sensitive terminal side effects never bypass the host:
- Pure app code emits
Effect.Request(Request { port, id, payload }). ticksurfaces those requests inTick.requests.- The host decides policy — for example,
examples/tui/driver/lib.tnrequires explicitallow_copy: bool(--allow-copy) for clipboard writes and explicitallow_notify: bool(--notifyviarun_options_full) for terminal notifications — and passesapproved: booltotui.present.encode_request(request, approved) -> result<bytes, str>. - Supported request ports (all emit bytes only when
approved == true; unapproved or invalid payloads returnerr):clipboard.osc52: UTF-8 payload, capped at 64 KiB, Base64-encoded into OSC 52.terminal.bell: empty payload, emits BEL (0x07).terminal.notify: sanitized UTF-8 payload capped at 256 bytes, emits OSC 9 (ESC ] 9 ; ... ESC \).terminal.progress:"<state>;<percent>"(statein0..=4,percentin0..=100), emits OSC 9;4 (ESC ] 9 ; 4 ; state ; percent ESC \). See ADR-0285.
7. Presented-frame approvals
Never approve a consequential action based on state that has not been painted to the user's screen yet. A fast feed can enqueue a new approval at 5 ms and a keypress can arrive at 6 ms before the 16 ms frame renders.
- After the host writes the bytes from a
Tick, the runtime deliversEvent.Presented(frame)andEvent.Stats(metrics)before the next input. - Both events are metadata-only: updating state in response to them does not schedule a redraw, avoiding an idle render loop.
tui_dashboardenforces this pattern:dashboard.approveanddashboard.denysucceed only when the complete pending approval prompt, the latestUNCERTAIN: DO NOT RETRYnotice, and theQ:nglobal queue count match the lastEvent.Presentedframe (including every page of a multi-page review). See ADR-0225.
8. Testing
Layer deterministic checks from fastest to heaviest:
- In-language unit tests (
testblocks): Placetest name { ... }beside widget/model code usingassert(cond)andassert_eq(a, b)(spec/LANGUAGE.md,spec/application-tests.md). Run on both C and the interpreter:tenon test plugins/tui_widgets .tuiscenarios: DriveAppwithout a TTY viatui.scenario.run_scenario(app, source)using directivessize W H,caps COLOR [sync] [cluster] [kitty],at MS,time MS,clock,resize W H,key NAME,bytes [HEX],paste [TEXT],feed [TEXT],feed-hex [HEX],expect screen ... end, andexpect bytes [HEX]. Seeexamples/tui/template/template.tui.- Plain and styled snapshots: Use
tui.present.screen_text(frame)for plain cell grids andtui.present.screen_snapshot(frame)when style runs matter (adds a deterministic style legend). - Session record and replay: Capture live
sessions opt-in via
examples/tui/driver/lib.tn'srun_options_record(--record PATH), which usestui.scenario.recording,recording_caps,record(64 MiB cap), andrecording_text. Replay and diff deterministically withtui.scenario.replay_check(app, recorded, expected_screen, expected_out),screen_diff, andbyte_diff. - PTY live check: Run
python3 -B examples/tui/check-live.py(examples/tui/check-live.py) on a controlling terminal to verify raw mode, Kitty push/pop, exact termios restoration, and frame parity against scenario goldens.
9. Headless twin
(tui_headless)
Interactive agent apps should degrade cleanly in pipes, CI, and non-TTY scripts:
- Probe descriptors with
tty.lib.is_terminal(fd)(0stdin,1stdout,2stderr;plugins/tty/DOCS.md). Undertenon interp, pass an explicit--formatflag because the FFI helper sees its own descriptors. - Decide output mode purely with
tui_headless.mode.choose_output(stdout_tty, stdin_tty, requested, no_color, term) -> result<OutputMode, str>:requested == "": choosesFormat.Tuionly when both stdin and stdout are TTYs andterm != some("dumb"), otherwiseFormat.Text."text","json","jsonl": selects that headless format."tui": succeeds only ifstdout_ttyis true (otherwise host exits2).coloris true only whenstdout_tty && no_color.is_none() && term != some("dumb").
- Render validated
tui_dashboard.feed.WireEventvalues withtui_headless.render:headless(output),step(state, event) -> Rendered,finish(state) -> Rendered, andexit_code(state) -> i64. - Headless mode never approves. Pending
approvals print to stderr and yield
exit_code == 3until resolved by external daemon policy (approval_ackorapproval_cancelled); notices yield exit1, clean completion exits0.
Reference: plugins/tui_headless/DOCS.md.
10. Theming and hyperlinks
Import
tui_theme.theme { Theme, default_theme, light_theme, theme_for }
(plugins/tui_theme/DOCS.md).
Theme defines eleven semantic Style
tokens: text, muted,
accent, selected, border,
danger, success, link,
diff_add, diff_remove, and
diff_context.
default_theme()andlight_theme()use terminal defaults and the 16-color palette (with bold accent/danger and underlined links) so user terminal palettes still apply.- Automatic light/dark selection:
tui.probedecodes OSC 11rgb:background replies intoCaps.background(-1when unknown, else0xRRGGBB), andtui.probe.luminance_dark(caps) -> option<bool>classifies dark vs light. Calltui_theme.theme.theme_for(caps)to picklight_theme()on light backgrounds (relative luminance > 0.5) and fall back todefault_theme()on dark or unknown backgrounds. - Override tokens with ordinary record updates:
let theme = theme_for(caps) with { accent: Style { fg: color(6), bg: color(0), attrs: 1 }, } - Pass resolved
Stylevalues into widgets rather than global theme state. - OSC 8 hyperlinks: Attach a clickable URL to
any span with
tui.types.span_link(text, style, url)orspan_link_policy(text, style, url, cluster)(read back withspan_link_of(span)). URLs are checked bytui.types.link_ok(url)(http:,https:,file:,mailto:, printable ASCII0x21..0x7E, ≤ 2,048 bytes; disallowed URLs drop to""while text still renders).tui.present.encodeemits OSC 8 open/close sequences and closes any active link at every row and frame boundary;screen_snapshotrecords a deterministiclinkslegend when links are present.
11. Prompt editing, completion and inline scrollback
Multi-line prompt
editor (tui_editor)
Use plugins/tui_editor/DOCS.md
for agent prompts while keeping tui_widgets.input for
single-line inputs:
- Initialize with
tui_editor.edit.editor(default_limits())(oreditor_with_text/with_history).Limitscaps buffer size (default 1 MiB), undo depth (100), history (500), paste collapse thresholds (10 lines / 2,048 bytes), andundo_ctrl_z(setfalseif the host reservesCtrl+Zfor suspend;Ctrl+_always undoes). - Feed events to
tui_editor.edit.update(editor, event) -> EditStep { editor, submitted, changed }:Enterreturnssubmitted: some(submit_text(editor))(expanding paste chips), pushes history, and clears the draft.Shift+Enter(when Kitty keyboard is negotiated),Alt+Enter, andCtrl+Jinsert a newline.- Large pastes collapse to atomic
[paste #N +L lines]chips (find_chips,expand_chip_at_cursor,expand_paste). Up/Downat buffer edges walk history;Alt+P/Alt+N(history_search_prev/history_search_next) filter strictly by prefix.
- Render with
tui_editor.view.editor_view_policy(editor, size, style, chip_style, cluster) -> EditorView { block, cursor, rows }and size dynamic viewports witheditor_height_policy(editor, width, max_rows, cluster). TranslateEditorView.cursorto screen coordinates so terminal IME candidate windows attach at the live caret.
Fuzzy
completion and command palette (tui_complete)
Use plugins/tui_complete/DOCS.md
with caller-supplied vec<Candidate> data (no
I/O or closures):
- Subsequence fuzzy matching:
tui_complete.fuzzy.fuzzy(query, candidate)andrank(query, candidates, limit)score ASCII case-folded subsequences with exact, prefix, consecutive, path-separator, and word-boundary bonuses. - Trigger detection: Call
tui_complete.trigger.trigger_at_line(line, col, row)(ortrigger_at(line, col)) after editor changes:/at the start of line 0 yieldsKind.Command;@at line start or after whitespace yieldsKind.Mention. Apply an acceptedCandidatewithtui_complete.trigger.apply(line, trigger, cand.insert)andtui_editor.buffer.buffer_set_line(...). - Completion popup: Create with
tui_complete.popup.popup(items), update the query withrefilter(p, query), handle navigation/accept/dismiss withpopup_update(p, event)(orpopup_update_paged), and render a non-modal cursor-anchored overlay withpopup_view_policy(p, anchor, screen, max_rows, style, match_style, selected_style, cluster)(auto-flips above the anchor near the bottom of the screen). - Command palette: Construct with
tui_complete.palette.palette_from(commands)(fromtui_shell.plugin.CommandSpec),palette_from_bindings(commands, bindings), orpalette_from_candidates(items). Toggle withpalette_open/palette_close, drive withpalette_update(p, event) -> PaletteStep { palette, run }, and render a centered modal layer (modal: true) withpalette_view_policy(p, screen, theme, cluster).
Inline
scrollback commit (tui_inline) and transcript search
(tui_dashboard.transcript)
- Inline mode (
tui_inline): Keep a bottom-anchoredViewport(viewport_policy(previous, anchor, caps.cluster)whereanchor.y + anchor.h == size.h). Paint the active prompt/status viewport withpaint(vp, block, caps)and resize height withgrow(vp, height, caps)orreanchor(vp, anchor). When a turn finishes, callcommit(vp, rows, caps) -> result<Painted, str>: it emits bottom-row LF in chunks ofH - h(without alternate screen or DECSTBM), paints the committed strips above the viewport, repaints the live viewport below, wraps the whole commit in synchronized output (?2026h/?2026l) whencaps.syncis true, and incrementsvp.committed. On resize or width-policy change, callinvalidatefollowed byrebase_policyandreanchor. - Alt-screen transcript search
(
tui_dashboard.transcript): Search laid-out rows withrow_text(t, row),find(t, query, from_row, forward) -> option<i64>(ASCII case-insensitive, single-row, no wrap-around),find_all(t, query, case_sensitive) -> vec<Match>,next_match(matches, current, forward, wrap), andjump_offset(t, row, height).
12. Security notes
- CWE-150 control-character sanitization:
tui.types.span,span_policy, andtui.unicode.sanitizereplace terminal control characters withU+FFFD. Untrusted text from feeds, filenames, or model output cannot inject raw escape sequences into strips or headless output. - Single escape-encoding boundary: Only
tui.present.encode/presentandtui.present.encode_requestemit ANSI/OSC bytes. Widgets and apps construct data (Block,Screen,Request), never terminal control strings. - Capability isolation: Pure UI packages
declare
capabilities = []and are checked bytenon plugin check. Only the outer host binary holdstty/fsauthority. - Session recordings contain keystrokes: Opt-in
--recordtranscripts capture raw input bytes, including pasted secrets and tokens. Treat recordings as sensitive, redact before attaching to bug reports, and note thatcli.Fs.writedoes not set mode0600automatically. - Restricted hyperlink URLs:
span_link/span_link_policypermit only printable-ASCIIhttp,https,file, andmailtoURLs up to 2,048 bytes (tui.types.link_ok); disallowed URLs are dropped while still rendering text.
13. Recipes
A ticking spinner, progress bar, and scrollable table
Use tui_widgets.spinner,
tui_widgets.progress, and
tui_widgets.table (plugins/tui_widgets/DOCS.md)
so idle apps keep Tick.wait_ms == -1 and schedule
wakeups only while active:
- Spinner: Construct
spinner_dots(),spinner_line(),spinner_ascii()(safe forTERM=dumbor legacy terminals), orspinner_for(ascii, now). OnEvent.Tick(now)while busy, emitspinner_tick(spinner, now)(Effect.Frame(spinner_next_ms(spinner, now))). Stop emittingEffect.Framewhen idle sowait_msreturns to-1. Render withspinner_view_policyorspinner_view_elapsed_policy(0.5s,1m05s). - Progress bar: Compute percentages with
progress_percent(done, total)and render Unicode eighth-block bars (▏..█, or ASCII#/-whenascii == true) viaprogress_view_policy,progress_bar_policy,progress_labeled_policy,progress_indeterminate_policy, andprogress_indeterminate_bar_policy. - Scrollable table: Define
Column { title, track, align }(0left,1right, usingtui_layout.flextracks) andTableState(table_state()). Handle keyboard/mouse navigation withtable_update(state, event, total, height, slot)and render only visible rows withtable_view_policyortable_render_policy(...) -> TableRender { block, visited }.
A virtualized transcript
Store laid-out blocks in
tui_dashboard.transcript.Transcript
(transcript(width) and
append(state, rows)). At view time, call
window(state, offset, height) -> Window { rows, visited }:
it binary-searches cumulative row counts and visits only the
visible rows, keeping per-frame work proportional to viewport
height rather than total transcript length. Rebuild the transcript
cache when width or Caps.cluster changes.
Streaming Markdown
Keep a tui_md.lib.Markdown
(markdown_policy(width, cluster)) in state (plugins/tui_md/DOCS.md):
- Buffer incoming byte deltas in a partial-line
tail: str. - On each
\n, feed the completed physical line topush_line(md, line)— closed blocks stay cached and are not re-laid out. - Render the unfinished active line with
tail_rows(md, tail)so streaming tokens appear immediately without reformatting closed history. - On resize or policy change, call
resize_policy(md, new_width, new_cluster), and callfinish(md)when the stream ends.
A modal confirmation
- Keep
confirm_open: boolandshown_prompt: strin app state. - Render the dialog with
tui_widgets.border.border_policy(body, dialog_size, "Confirm", theme.border, cluster)and place it on a higherzlayer withmodal: true:Layer { rect: dialog_rect, block: framed, z: 10, modal: true } - On
Event.Presented(frame), record whether the full confirmation text was actually presented inframe(tui.present.screen_text(frame)). - Accept
y/Enteronly whenconfirm_openis true and the prompt matches the last presented frame; allown/Escto dismiss immediately.
Explicit
workflow & modal state (derive StateMachine +
fsm_test)
For multi-step modals, approval flows, or connection/job
lifecycles where illegal transitions should fail at compile time,
back the workflow with derive StateMachine (plugins/fsm/DOCS.md,
plugins/fsm_gen/DOCS.md):
- Declare a state catalog
structwith@initial,@terminal, and repeatable@on("<event>[(<Payload>)] -> <t1>[, <t2>...]")attributes, then addderive StateMachine for <Name>:fsm_genvalidates the graph statically (FSM001–FSM010, failing closed withE0966on unreachable states, dead-end non-terminal sinks, or conflicting event payloads).- Emits
<Name>State,<Name>Event, narrow<Name><State>On<Event>branch enums (making illegal target states unrepresentable), required<Name>Handlers, and a zero-wildcard<name>_step<H: <Name>Handlers>(h, state, event) -> result<<Name>State, InvalidTransition>.
- Gate
app_actionsaffordances directly from the FSM:- Call
<name>_allowed_events(state) -> vec<str>(or<name>_can_handle(state, event)) inside yourActionAppspec builder and pass the result toapp_actions_gen.rt.disable_if(spec, !allowed, "not allowed in " + <name>_state_name(state))so UI controls and AI agents see only currently legal actions.
- Call
- Explore and shrink automatically with
fsm_test:- Run
fsm_test.graph.explore_graph(default_config(), <name>_graph(), init, events, step_res, <name>_state_name, <name>_event_name, <name>_is_terminal, invariant)inside atestblock. - Assert
report.explore.passed(checks all 5 universal oracles:InitInvariantViolated,NonDeterministic,TerminalEscaped,StateCorruptedOnReject,InvariantViolated) andfsm_test.graph.is_full_coverage(report.coverage). - On failure or gaps, print
fsm_test.lib.format_regression_tn(...)for a copy-pasteable minimizedtestblock orfsm_test.graph.coverage_mermaid(<name>_graph(), report.coverage)to inspect[UNCOVERED]edges.
- Run
14.
Agent-Controllable Stateful Apps (app.actions/v1.1,
derive Actions & Live Co-Pilot)
Expose any pure TUI state machine to AI agents and
human-in-the-loop co-pilots without PTY scraping by pairing app_actions,
app_actions_gen,
app_actions_mcp,
app_actions_tui,
and optionally app_actions_client
(see ADR-0292
and ADR-0293).
Decision rule: Use
derive Args+args_mcpfor stateless CLIs; useapp_actions+derive Actions+app_actions_mcp/app_actions_tuifor stateful interactive or co-pilot apps.
1.
Define actions with derive Actions (or fluent
schema/args helpers)
- Recommended (
derive Actions,plugins/app_actions_gen): Declare a single catalogstruct(withunitfields for zero-arg actions or typed payload structs) or actionenumannotated with@prefix("t."),@name,@doc,@risk("read" | "write" | "destructive"),@approval, and field constraints (@min,@max,@choices), then runtenon gen <file.tn>.- Generates
<Target>Cmd,*_specs() -> vec<ActionSpec>,*_decode(name, args_json) -> result<..., str>, and*_compact_catalog() -> str, validating every generated schema againstmcp.wire.schema_supported(..., 0)at codegen time (failing closed withE0966on unsupported types). - Keep curated bounded
project_stateprojections and dynamic liveenabled/disabled_reasonpredicates in explicit pure.tnmethods (usingapp_actions_gen.rt.disable_ifandwith_int_max). - Proven in
examples/tui/todo/actions.tn: refactoring from hand-written schemas/decoders toderive Actionscut ordinary source from 159 → 79 LOC (-50.3%) while passing all livetodoMCP benchmark scenarios.
- Generates
- Hand-written fluent builders
(
app_actions.schema&app_actions.args): When building dynamic actions without codegen, useschema_obj()(.req_str,.opt_str,.req_i64,.opt_i64,.req_bool,.req_enum,.req_str_arr,.to_json()— always emitting"additionalProperties": false) andparse_args(args_json)(ArgsViewtyped extractors). - Compact
<ns>.<verb>naming: Prefer short 1–2 token dot-namespaced verbs (t.new,t.split,t.run,td.add) and short arg keys (id,dir,cmd,txt,q) soformat_compact_catalogkeeps prompts tiny.
2. Pure v1.1
session engine (app_actions.session)
- Persisted revisions: Start sessions with
new_session_at(app, initial_rev, cfg)so restarts preserve monotonicstate_rev(< 1clamps to1). - Pure
dry_runpreview:execute_dry_run(s, call, presented_approval_id)checksexpected_rev, enablement, args, andharness_policy(PolicyDeniedfails closed), computes the redactedWireUpdatepreview andrequires_approvalflag, and leavess.app,s.rev, history, and effects untouched. - Transactional multi-step batching:
execute_batch(s, calls, expected_rev, atomic, presented_approval_id, duration_ms)executes1..=16steps sequentially against evolving immutableA, returning one coalescedWireUpdateand advancingrevby1on commit. OnApprovalRequired, returnsBatchStatus.PausedForApproval(committing the safe prefix whenatomic == falseor rolling back cleanly whenatomic == true). - Immutable undo & rollback:
ActionSession<A>retains a bounded ring of prior immutableAvalues (up to 32 revisions).undo(s)androllback_to_rev(s, target_rev)restore the exact prior state and advancerevmonotonically (never reusing old revisions).
3.
Live Co-Pilot TUI overlays & discovery
(app_actions_tui)
- Shared
state_rev&Ctrl-Kcommand bar (app_actions_tui.copilot): Wrap your pureActionAppinCopilotState<A>(copilot_init). Route human updates throughon_tui_stepso human edits bumpstate_revand invalidate stale agent calls withStaleRev+ catch-up delta. Route keys throughhandle_copilot_key(Ctrl-KopensCopilotMode.Prompting; all keys and pastes are isolated from the underlying app whilemode != Idle, andEffect.Timeris emitted only whileAwaitingModel). - ADR-0225
dry_runapproval modal (app_actions_tui.overlay): Compose overlays in one call withcompose_with_copilot(base, c, size, caps)(threadingcaps.clusterandtheme_for(caps)). OnDestructive/requires_approvalsteps (including mid-batch pauses viaon_agent_batch), the modal renders the boundeddry_rundelta preview (<= 6lines) with[y] Approve [n] Deny [u] Undo batch.yandconfirm_pending_approvalfail closed withapproval_not_presenteduntilEvent.Presentedproves the modal was painted;headless_mode == truenever auto-approves (exit_code == 3). - Live
Event.Feedwire & discovery (app_actions_tui.wire): Route incoming Unix-socket / feed JSON-RPC lines throughCopilotWire<A>(on_feed_event,1 MiBframer cap, emittingEffect.Request(port: "copilot.reply", ...)). Advertise running instances under~/.cache/tenon/apps/($XDG_CACHE_HOME/tenon/apps) usingDiscoveryRecord,discovery_record_path, anddiscovery_socket_path(sun_path <= 104bytes).
4. Expose over MCP
(app_actions_mcp)
- Projects any
ActionApponto 3 flat-token tools (app_state,app_actions,app_act, 334 estimated schema tokens, well under the<= 900cap) over chunked stdio (mcp_server.stream) or loopback HTTP/SSE (mcp_server.sse). app_actionssupportsformat: "full" | "compact";app_actsupports single-callname+args,batch: [{ name, args? }](1..=16,atomicdefaulttrue), anddry_run: true(returns preview withstate_changed == false,effects == []).- MCP
2026-07-28requests include"_meta": {"io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {}}.
5.
Optional Local Action Model (app_actions_client &
action_model_ctl)
- Pure client (
plugins/app_actions_client,capabilities = []):prompt.build_action_plan_promptformats a tiny non-thinking prompt from the bounded projected state (<= 2048 BUTF-8 safe) andformat_compact_catalog(specs, true).parse.parse_action_planparses strict CD3 plans ({"plan":[{"a":"t.split","p":{"dir":"v"}}],"ask":null}or{"plan":[],"ask":"..."}), rejecting prose/fences, unknown actions, invalid args, and any forged approval/bypass key anywhere in the JSON tree.openaidefaults to loopbackhttp://127.0.0.1:18085/v1/chat/completions(temperature: 0.0,enable_thinking: false,allow_remote: false).
- Optional userland manager
(
tools/action_model_ctl): Zero weights ship in thetenonbinary (ADR-0291); apps work 100% offline via keyboard and--mcp-actions. Users who opt in manage SHA-256-verified GGUF packs and the loopback:18085llama-serverwithtenon run tools/action_model_ctl/main.tn -- status|install|start|stop|bench.
6.
Reference Capstone (copilot-term) & Redaction
Note
copilot-term(standalone companion repository): Standalone pure-VT100/ANSI multi-tab, split-pane Tenon terminal multiplexer with nativeproc.libPTYs, a 13-actionderive Actionscontrol plane (t.new,t.split,t.focus,t.rename,t.tail,t.run,t.send,t.sig, …),Ctrl-Klive Co-Pilot bar, ADR-0225dry_runapproval modals on shell-execution/destructive commands,--mcp-actionsstdio mode, and--copilot-socklive attachment.- Redaction naming gotcha
(
state_delta.redact):default_redact_policy()matches"token"as a case-insensitive substring of object keys. Avoid naming non-secret telemetry fields"input_tokens"/"output_tokens"(prefer"input_usage"/"output_usage"or supply a customRedactPolicy).