app

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2026 License: AGPL-3.0 Imports: 39 Imported by: 0

README

app

The Bubble Tea application layer: the view and key routing. Lifecycle goes through core, by request. app keeps everything that renders or reads a pane client, m.state, overlays, key dispatch, the Lua engine and script host, the workbench and review, the overview cursor, tab bar, menu and error bar, the split-ratio throttle, full-screen attach, the issue picker (its fetches are core.Model.FetchIssue requests), and the views of accounts and GitHub state. It holds none of the model's objects: no *session.Instance, workspace, registry, storage or state.

How it runs

  • app.go owns the home model and its Update/View (Model-View-Update). home.Update is a thin wrapper: it runs the message switch (update), then drainCore (app/core_glue.go), which empties the client with core.Core.Sync, then publishSelection, which tells the model the selected row (SetSelected) when it moved.
  • Keys route in two stages: handleKeyPress dispatches by m.state to a per-state handler in app/state_*.go; in the default state, keys flow through the Lua engine via app_scripts.go's dispatchScript, which consults script.Engine.HasAction and returns a Cmd that drains the resulting scriptDoneMsg. The keymap is script/defaults.lua; user scripts in ~/.loom/scripts/*.lua rebind or add keys.
  • The TUI holds the daemon's client as home.core (a core.Core, in production an rpc.Client) and, for the link's state and wakes, as home.conn (the *rpc.Client; nil in bare test homes, which skip every link check), with its closer home.stopCore. Run defers the close as a closure (defer func() { h.stopCore() }()), because a rejoin replaces the client and its closer. A forwardWakes goroutine per client turns each coalesced wake into a coreWakeMsg: Run starts the first, resync one for each client a rejoin brings. It never blocks the client's reader or the model's loop, since p.Send waits for Update.
  • Sync never leaves the client. It returns the state events for what changed since the last Sync (WorkspacesChanged, ModelChanged, AccountsChanged, GitHubChanged, then each changed workspace's ViewsChanged, coalesced to the newest), then the other events in arrival order; applyCoreEvent applies each.
  • app/core_glue.go is the seam: coreWakeMsg/forwardWakes carry the wakes, drainCore/applyCoreEvent apply events, publishSelection tells the model the selection, newSlotView builds a slot over a workspace's view, and slotFor finds the slot showing a WorkspaceID.
  • When the client loses the model (the daemon stopped, crashed or was replaced), the TUI goes offline and joins a daemon again (next section); only a newer daemon found on rejoining ends it (ErrDaemonNewer, kept in home.exitErr, which Run returns and main.go reports once the terminal is restored). Saves are the daemon's: handleQuit flushes the split ratios and persists the open list, and saves no session.
  • The model keeps ticking and applying results while the TUI's event loop is blocked (a full-screen attach, $EDITOR, claude auth login); its events wait, coalesced into one wake.
  • The TUI reaches tmux by session name, never through an instance, on the daemon's tmux server (pinned by main.go before Run): the full-screen attach builds tmux.NewSessionNamed(name, program), and the liveness guards call m.sessionAlive(name) (a has-session probe; tests set its aliveProbe seam). Its own environment still decides what it starts itself: the terminal pane's shells (their update-environment variables), a relative or ~ ctx:new_instance{path=…}, which it makes absolute (scriptPath) before the Create, and a login from the Accounts screen.

home.Update runs the message switch, the drain (drainCore), then checkLink, then publishSelection: the link is checked after the drain, so the replies that arrived before the connection closed are applied before the requests still waiting are failed as stranded. home.link is one of:

  • connected: the client is the daemon's.
  • stopping: the client heard a bye (rpc.Client.Stopping). It takes no request, the replies of the requests in flight still come, and the banner reads "the loom daemon is stopping: finishing its jobs in flight".
  • waiting: the connection closed after a bye (a graceful stop, or a newer loom replacing the daemon; the client's Err matches core.ErrUnavailable). The TUI polls for a daemon once a second (waitPoll, a rejoin that never spawns) and starts none itself; ctrl+r starts one. Banner: "the loom daemon stopped: waiting for one to start (ctrl+r starts it)", then the last rejoin's note.
  • reconnecting: the connection closed with no bye, or the model failed (a crash). The TUI redials on a backoff (rejoinBackoff: 1s doubling to 30s), starting a daemon when none runs; after maxSpawnFails (3) daemons that did not start (ErrDaemonDidNotStart, a daemon that exited before serving) or did not stay up (a rejoined link lost within stableLink, 30s, of coming up: link.upAt, read through the home.now clock seam), it drops to waiting. Only a link that stayed up 30s, or ctrl+r, resets those counts, and the backoff goes on from its last attempt meanwhile, so a daemon that serves and dies again is not restarted every second. Banner: "lost the loom daemon: reconnecting (attempt N)", the note, "ctrl+r retries now".

Offline (any state but connected) the banner takes one row above the account strip and tab bar (bannerHeight, counted by topChromeHeight). The TUI keeps showing and attaching panes, since they talk to tmux, and keeps the last published views and statuses. lose applies what the client received before the loss, closes the client and fails every request still waiting; while stopping, failStranded fails only those made after the bye (ReqID above link.byeReq) and those the client refused as unavailable (TakeRefused). Each is failed with a synthetic Reply{Err: core.ErrUnavailable} through handleReply, so a lifecycle request shows "kill x: the loom daemon is unavailable", a prompt send releases its hold, a Lua call resumes raising "<op>: the loom daemon is unavailable", and a create or an issue fetch shows its error.

The offline key gate. In the default state offlineKeyAllowed passes the keys that talk to tmux or stay in the TUI (navigation, ]/[, tab, the rail, the terminal pane and the split, the workspace tabs, attach in all four forms, t, d, f, c, e, scrolling, the workbench's panel digits, help, q, enter, esc, z). Every other key (n N I D p s m r R W S a among them) shows "the loom daemon is <stopped|stopping|unreachable>: needs it" and does nothing (offlineKeyRefused). The gate goes by the key's name, not its binding: a user script bound to an unlisted key is refused, while one bound to a listed key still runs, and the client refuses whatever request it makes (the backstop below). ctrl+r is a rejoin now (retryNow: starting a daemon, whatever the state's own schedule; refused while stopping, "still stopping: it finishes its jobs in flight first", and while a rejoin runs); connected it is an unbound key. The workbench's markdown editor and review pane take their keys before the gate (workbenchOwnsKeys). Overlays and modal states are not gated: a commit made after the link dropped reaches the client, which refuses the request itself (core.ErrUnavailable, a refusal), and the request's ReqID carries the refusal to the user.

Rejoin. main.go hands app.Run a Rejoin function (rejoinDaemon: the startup join, quiet, with a spawn flag; its progress reaches the banner as rejoinNoteMsg). rejoinTick starts an attempt when a tick of the link's current generation fires (link.gen is bumped on every change, so a stale tick or result is dropped); rejoined applies its result: a client joined is resynced, a newer daemon ends the TUI, a failure becomes the banner's note and schedules the next attempt. The newer build wins as at startup: the same build is rejoined, an older daemon is replaced once (under replaceGuard), a newer one makes the TUI exit.

Resync (resync, on Update) swaps in the new client (core, conn, stopCore, a forwardWakes for it) and brings the TUI up to date:

  • The new client's first Sync carries its snapshot, which the appliers apply: rows, workspaces, accounts and GitHub state. Rows keep their selection because an InstanceID names one record on every daemon.
  • It rereads the registry (ReloadRegistry), closes the tabs whose workspace the daemon no longer serves ("X is no longer registered; closed its tab", or global mode when none is left), and Opens every workspace it shows (the new daemon's first open: its terminal and GitHub polling start; a failed open shows its error).
  • It sends the UI prefs and the focused tab changed while offline (unsentPrefs, unsentLastUsed: offline, mutateUIPrefs and persistFocusedWorkspace apply the change locally and keep it, and the TUI's value wins over the published one), has the selection published again (sentSelected = 0), and, when the daemon names another tmux server (the old one died), re-pins it and replaces every pane client (releaseAllPanes, then the repair paths).
  • Drafts, overlays, the workbench, the review and scroll positions are left as they are. The info line reads "reconnected to the loom daemon".

Quitting offline (q) writes nothing, since the open list and the ratios are the daemon's to write: it logs quit.offline_unsaved with what was lost. Tests: app/link_test.go (TestLink_…, TestOfflineKeyGate, TestOffline_UIPrefsApplyAndAreSentOnResync), app/reconnect_test.go (TestReconnect_…: a second daemon booted from the same disk) and app/daemon_client_test.go (TestDaemonGone_GoesOffline).

The model boundary

  • The TUI talks to the model through core/rpc/'s client. Every rpc:local query in core/iface.go reads the client's replica; requests cross the wire and their events arrive before their reply, which is why the read-back sites (syncViews, syncWorkspaces, the drains right after a transition, the nested drain in newLaunchOptionsOverlay) see a request's effect with no extra round trip. A cast gives no such guarantee. m.core locks its own replica, so calling it from a Cmd body would not race, but it would read state no drain has applied.
  • TestTUIHoldsNoModelObject (internal/testenv/instance_enforce_test.go) fails on any production use in app/, ui/ or script/ of session.Instance, its constructors or options, session.Storage, the launch toggles' setters, core.Workspace, core.Model, core.New, core.Loop, core.Start or core.Job, config.WorkspaceRegistry/LoadWorkspaceRegistry, config.AppState/State/LoadStateFrom or config.SaveConfigTo, or account.Registry, under whatever name the file imports the package, and on the deleted bridges (InstanceOf, IDFor, AdoptForScript, instOf) anywhere.
  • Registry writes go through the model on Update: the startup registration prompt's Cmd returns registerWorkspaceMsg, and Update calls Register.

Workspaces and slots

  • A workspace the TUI shows (a tab, or its classic workspace while no tab is open) is a slot (workspaceSlot, app/workspaces.go): {id, info, views, list, splitPane, workbench}, a view of a workspace the model serves, named by core.WorkspaceID. home embeds *workspaceSlot, the focused slot, so m.id, m.info, m.list, m.splitPane, m.workbench and the accessors (name(), label(), settings(), uiPrefs(), recovery(), m.repoPath(), m.configDir()) resolve to that slot's own. m.slots (a []*workspaceSlot) holds the tabs in order, so every open slot's state is always current, with no save step and no i == m.focusedSlot branch to pick the live copy; openSlots() yields them, or the classic slot alone, for fleet-wide walks.
  • Which workspaces the TUI shows is its own state, not the model's: m.slots, the classic slot, home.startupName (the workspace the classic slot shows at startup: "" for the global one, a registered name for loom <dir> or --workspace), home.failedOpen (saved tabs that failed to open, kept in the open list) and home.program (the agent program drafts default to, from -p, else the startup workspace's config).
  • Invariant (checkSlotInvariant, asserted in tests): every slot shows a workspace the model serves (IsLoaded(slot.id)); no slot appears twice and no two tabs show one workspace; with tabs open, m.workspaceSlot == m.slots[m.focusedSlot]; with none it is the classic slot (not in m.slots), showing the startup workspace or, once enterGlobalMode ran, the global one; never nil, and every slot has a splitPane and workbench. Only a bare test home shows no workspace (m.id == 0).
  • Transitions (app/workspaces.go, app/app_init.go), each showing a workspace through Core.Open and draining right after: startup and the saved-tab restore (startHome, restoreSavedWorkspaces); opening a tab (openTab, activateWorkspace); closing one (deactivateWorkspace, which refuses the last tab); global mode (enterGlobalMode, which opens the global workspace before dropping anything; stayInGlobalMode for a Global commit made from global mode, which rebuilds nothing); the picker's commit (applyWorkspaceToggle, which keeps the open tabs when every desired workspace fails); registration (registerWorkspaceMsg: Register, then openTab, or global mode when the directory is the global workspace's). openList is the tabs in order, then failedOpen; persistOpenList writes it through Core.PersistOpenList.
  • servedID finds a served workspace by name in Core.Workspaces, after a ReloadRegistry for one registered or renamed since (the reread serves it, or renames it in place). It refuses a name whose directory the model serves under another (servedFor, comparing directories as the model does, sameDir): a twin, the other name still registered ("X is the same directory as Y, which loom serves: open Y"). Startup and the restore open the served twin in its place instead, with a one-time note shown with the recovery summary (twinOf, twinNote, addNote, showStartupInfo).
  • A running TUI follows what the daemon serves (applyCoreEvent, on WorkspacesChanged). closeUnservedLive closes the tabs whose workspace the daemon stopped serving (loom workspace remove, a registry reread), with the info line "X is no longer registered; closed its tab" (global mode when none is left); it does nothing while the link is down, since a rejoin's resync closes them itself. renameShown follows a workspace renamed by ID (home.servedNames holds the last names; a rename keeps the ID): the tab bar and each rail's header are redrawn and a saved tab in failedOpen takes the new name.
  • A workspace registered at $HOME shares the global config dir, so the model serves it as the global workspace: startup on it shows global ("home shares its config dir with the global workspace; showing global"), a saved tab of it opens nothing, with a note, the picker refuses it ("… which loom serves: pick Global"), and registering it (loom ~) shows global with the same note.
  • A saved tab that fails to open at startup stays in failedOpen and shows checked in the picker, labelled "(failed to load)", so later launches retry it, until it opens or the user deselects it; global mode closes them all. When every restored tab fails, the classic slot opens the startup workspace; if that fails too, the error is shown instead of exiting, and new sessions are refused while the focused storage refuses writes (latchedStorageErr).
  • Dropping a slot (closing a tab, the classic slot giving way to the first tab, enterGlobalMode dropping the tabs or a classic workspace slot) returns prunePanes and releaseSlotCmd, which detaches the attach clients its terminal pane holds on loom_term_* shells (TerminalPane.DetachAll; the pane enterGlobalMode carries into the global slot keeps only the clients of sessions the global list holds, DetachExcept), and the caller runs instanceChanged.
  • Each slot caches its workspace's core.WorkspaceView (slot.info: name and paths, a config.Settings copy, UI prefs, help screens, storage flags, load error, recovery summary), replaced by each WorkspacesChanged and reread by syncWorkspaces after the TUI's own write. UI prefs (mutateUIPrefs) and help screens are SetUIPrefs/SetHelpScreensSeen requests; the view mode persists per workspace in state.json's ui block.
  • The settings overlay edits a config.Config of the TUI's own (m.settingsEdit, built by config.FromSettings), each change sent back whole as SaveSettings; a saved default program becomes home.program. A theme or default program another TUI saved for the focused workspace applies when its WorkspacesChanged arrives (applySettingsChange, app/state_settings.go: the theme painted, home.program replaced), and only when it changed.

Views, rows and drafts

  • Each slot keeps its workspace's core.InstanceViews as its view store (workspaceSlot.views, app/views.go): seeded from core.Core.Views (the client's replica) when the slot is built (seedViews), replaced wholesale by each ViewsChanged, and reread by syncViews where an Update reads back a change its own request just made.
  • Every reader sees the store through rowsOf (the rail's ui.InstanceSource is slotRows), which copies each row, lays the TUI's own overlays over it (overlay(): the bells of home.bells, set by a pane's bell and cleared by focus, and the ladder's scraped status in home.ladder) and appends the creation flow's draft row.
  • findRow/viewByID/viewBySession look a row up across every open slot, activeViews lists the active ones, refreshSelection repoints the split pane's and menu's copies (SetInstance) at the selected row on every store or overlay change (the focused slot's ViewsChanged, setLadder, newDraft/discardDraft, createReplied), and the ViewsChanged applier runs pruneBells/pruneLadder.
  • Creation flows edit a draft (app/drafts.go, m.draft): it shows as a row with ID 0 at the end of its own slot's rail until confirmDraft sends core.Model.Create, and every cancel path calls discardDraft (discardPendingLaunchOptionsCancel included).

Requests and completions

  • app/requests.go is the request book: newReq records what a request with a core.ReqID waits on (pendingCreate, pendingSend, pendingOp, pendingScript, pendingIssue) and handleReply routes its Reply. Every lifecycle request the user starts carries one (opReq, a pendingOp), so that refusal() can show a refusal through handleError.
  • A prompt send holds input to its instance until its Reply (sendPrompt, holdInput, m.sending); meanwhile sendingTo refuses inline attach and another send to it with an info line.
  • app/completions.go keeps the view's half of the completions (applyStarted, applyRecovered). Every client attaches the session's pane; only the one whose request it was (Started.Req/Recovered.Req non-zero) selects the row, attaches inline or shows a notice. For its own start, an owner that is the focused slot gets the row selected and inline attach (or, with another flow on screen, "X started"); a background owner gets the row selected in its own rail and "X started in Y". applyRecovered selects the same way, unless another flow is on screen, attaches nothing inline, and always confirms the recovery. An N flow's initial prompt is sent by a job after the start lands (sendInitialPrompt), and the model emits Started only once that send returns (deliverPromptSent), so no typed key can join the prompt.

Panes and the health tick

  • The TUI holds one attach client per live agent session in ui.PaneClients (home.panes), keyed by tmux session name; every pane render, scroll, cursor, mouse event, paste, inline-attach key and status scrape goes through m.panes.For(v) (ui.Pane, for a view v). A client is keyed by the view's TmuxSession, and its adapter (trust-prompt and pending-prompt patterns) comes from the view's SessionProgram (inst.Pane().SessionProgram() on the model side), never Program. Only an active row (InstanceView.Active(): started, not paused, not Loading, Deleting or Recoverable) gets a client, and the terminal pane starts a shell only for an active row (ensureSessionLocked, ui/terminal.go).
  • The attach points (app/panes.go) all run on Update: ensureSlotPanes at every workspace load; replacePane when a start, resume or recover lands in a loaded slot (core.Started, core.SessionLaunched, core.Recovered, a Lua inst:resume() included) and after a workspace terminal's auto-restart (core.SessionLaunched), since the old client watched the replaced session; ensurePane for the repair after the health tick's probe and after VerifyDead, both on core.Alive (live session, client not attached, no full-screen attach running: attachingID), after a returning full-screen attach, and after a reverted kill or pause (core.Reactivated).
  • Releases go through prunePanes, which Retains the active rows' session names and hands every other client to releaseClientsCmd, and per open slot detaches the terminal pane's clients of titles the slot has no live row for (keepsTerminal: started, not Paused, not Recoverable; TerminalPane.DetachExcept). The prune runs on the health tick, on core.ClientsStale (a kill or pause completing, KillResult/PauseResult, or an OpFailed) and at every slot drop. Instance.Kill and Pause end the agent's session and the terminal pane's shell in their jobs (CloseRelatedSession, by name), which gives each pump EOF; the prune releases both clients. A resumed, recovered or reverted row gets its shell with the refresh its completion triggers (InstancesChanged, Recovered).
  • A release runs PausePreview (detach, session left running) in a Cmd. The attach fd is blocking, so closing a client of a still-live session waits the full pumpWaitTimeout (signalPumpStop's deadline can't cut the read short), while a dead session's closes at once; releaseClientsCmd closes its clients in parallel. Full-screen attach (startFullScreenAttachMsg) still runs PausePreview on Update and pays that wait there; making the PTY pollable is a follow-up.
  • With the emulator there is no preview tick: panes re-render on paneDirtyMsg from the output pump, status transitions ride paneQuietMsg, and ptyDeadMsg runs VerifyDead's probe. The events (events.go, handled in update) report to the model by the ID of the row their session name resolves to (viewBySession): paneDirtyMsg calls MarkOutput (by session name: the dirty set the next probe takes, takeDirty) and PaneOutput, and paneQuietMsg calls PaneQuiet; both feed hook scans and the Prompting roster query.
  • The health tick splits along the pane boundary. The model's half (core.Model.Tick, core/tick.go) fires from the loop's own timer and favours every client's selected row (the server merges each client's SetSelected into the model's selection set, SetSelection, and the probe refreshes each one's full diff): one probe job (probeJob: liveness, parity, diff stats) over every active instance, whose HealthResult deliverHealth applies (applyLiveness pauses the dead and relaunches a dead workspace terminal under its circuit breaker, maxWorkspaceTerminalRestartFailures; an instance a kill, pause or resume moved to Deleting or Loading while the probe ran fails statusEligible and is skipped, liveness included); it dispatches the gated jobs that are due and stats accounts.json (maybeReloadAccounts). The loop re-arms it when the probe lands, so ticks never overlap a probe. The TUI's half (the tickUpdateMetadataMessage case in app.go, on its own tickUpdateMetadataCmd) expires toasts, prunes pane clients, runs the inline-attach backstop, the snapshot path's status scan (snapshotScan → snapshotStatusMsg) and the workbench scan; core.HealthChecked re-arms nothing here (it refreshes the workbench's diff tab). Under LOOM_PANE_RENDERER=snapshot (and on Windows) a 100ms preview tick and a 500ms health tick with a capture-pane status scan remain.
  • The status ladder (statusDetectedMsg on the event path, snapshotStatusMsg on the snapshot path, paneDirtyMsg's Ready→Running promotion) writes only m.ladder[id] (setLadder: a status and since when), which overlay() shows for an active row whose view has no reported status (!StatusReported); its gates read the row as shown. So the model's status of a non-Claude session is its lifecycle status (Running once started), which state.json saves; Ready and Prompting from the ladder live only in the TUI. For Claude sessions the hooks and roster report the status, and the ladder is the fallback.
  • Inline attach checks the focused pane's own session (focusedPaneAlive, state_inline_attach.go): the terminal pane's shell is a separate tmux session (loom_term_<title>), and tmux's last write to a dying client is the literal "[exited]".

View modes

  • The view modes are viewModes: m.viewMode (focus, overview, workbench) is orthogonal to m.state: overlays and per-state handlers work unchanged on top of it. tab toggles focus and overview; enter/esc return to focus; n/N drop to focus first.
  • Overview spans the open workspaces only, one card group each, with a global cursor (home.overviewCursor, translated to ui.OverviewCursor in overviewData). state_default.go gates script dispatch through overviewKeyAllowed, mouse events are dropped, and bell and attention badges clear only on entering focus. Cursor-committing keys go through focusCursorSlot() (loadSlot, then select), so enter, D, r and n reuse focus mode's intents on the right workspace.
  • Workbench mode (app/workbench.go) reuses the focus split for its left half: viewWorkbench force-hides the split's terminal (restored from wbPrevTerminalHidden by cleanupWorkbench, the single teardown, which leaveFocusedSlot calls) and shares its TerminalPane with the right panel through SplitPane.Terminal(). The markdown follow scan rides the health tick as a Cmd; scan, load and save results apply only in Update handlers, gated on the session title. Workbench mode is never persisted: a restart lands in focus.
  • The review tab (5/c) freezes markdown follow mode on entry and resumes it on exit (q) or teardown, and q returns to the tab the review was opened from (home.wbReviewPrevTab). Persistence runs as Cmds delivering reviewui.SavedMsg (non-fatal, shown in the footer). The pane claims only the keys it acts on (reviewui.claimsIdleKey), so idle esc, session ops, workspace navigation and, in doc mode, the panel-tab digits fall through to the workbench. home.wbReview (the concrete *reviewui.Pane) and the Workbench.SetReview interface field stay in lockstep; Workbench.SetSession drops its half on a title change, so every retarget goes through home.dropReviewPane (instanceChanged's workbench retarget does). The wheel feeds the pane synthetic cursor keys (reviewScrollKey).

Keys, modal states and mouse

  • handleMenuHighlighting defers a keypress matching a built-in binding (keys.KeyForString, a reverse lookup of the built-in table used only for highlighting) to a later Update through an async replay Cmd, tracked by one flag (m.keySent) that assumes the next KeyPressMsg is that replay. Full-screen modal states sit on its exclusion list. View() places the active overlay only for the states its switch names (statePrompt, stateHelp, stateConfirm, stateWorkspace, stateSettings, stateMergePicker, stateLaunchOptions, stateIssuePicker).
  • keys/ defines the enumerated KeyName values and keys.GlobalkeyBindings, which drive the help panel and menu highlighting only; dispatch is the engine's, and TestKeymapParity (app/keymap_parity_test.go) keeps the table in step with script/defaults.lua.
  • ctrl+c is hard-reserved in the default state, checked before the engine, so no script can trap the user in the TUI.
  • Mouse selection works over the rendered text: SplitPane.HitTest(mouse.X - m.listWidth, mouse.Y - m.topChromeHeight()). Mouse messages reach Update in every state; selection runs in stateDefault and stateInlineAttach, and the wheel has no state gate. In interact mode (app/interact.go) the left button is deferred: a drag becomes a loom selection copied to the clipboard, a plain click is forwarded into the agent (forwardClickToFocused). The clipboard is written by tea.SetClipboard (OSC 52, which tunnels over SSH) with a local fallback (app/clipboard.go). Interact mode exits on ctrl+q or a double esc (home.lastEscAt); a single esc reaches the agent.

Scripts

scriptHost (app/app_scripts.go) holds no *home. Script nav, scroll, diff and workspace primitives record a func(*home) through deferModelMutation, drained into scriptDoneMsg and applied on the main goroutine in handleScriptDone; those that move the selection or the focused slot go through deferFocusMutation and apply only in stateDefault, since the message can land after an awaited intent opened a flow. Reads (ctx:selected(), ctx:instances(), ctx:config_dir(), …) come from a snapshot newScriptHost takes on the Update goroutine when the dispatch or resume begins (views, minus the draft row). A script's lifecycle calls and ctx:new_instance are intents the host queues; handleScriptIntent turns them into model requests (scriptInstanceOp, scriptCreate), and each call's coroutine resumes when its Reply lands (scriptReplied, a scriptResumeMsg). The snapshot pins the focused slot and scriptDoneMsg.slot carries it back: handleScriptDone sends a ctx:new_instance as a Create in that slot's workspace only if it is still focused, decided before the script's deferred actions run; otherwise the call raises "new_instance: workspace changed while a script ran; not creating

Documentation

Overview

Package app is the Bubble Tea application layer: the controller that owns the home model, routes keyboard input, and composes the ui view components.

Keyboard dispatch is two-staged: handleKeyPress in app.go selects a per-state handler in state_*.go, and within the default state keys flow through the Lua script engine via app_scripts.go's scriptHost adapter. The canonical keymap is script/defaults.lua, which users can extend or override from ~/.loom/scripts/*.lua.

Concurrency: the Lua script.Engine is not goroutine-safe, so every dispatch runs under the engine's mutex via a tea.Cmd goroutine; the goroutine emits a scriptDoneMsg that the main loop consumes in handleScriptDone. Never touch Bubble Tea state from inside the Lua engine — queue it on scriptHost and finalize on the main goroutine.

Index

Constants

View Source
const GlobalInstanceLimit = core.InstanceLimit

GlobalInstanceLimit is the rows a workspace slot holds before the creation flows refuse another (core.InstanceLimit, checked through core.CheckRoom).

Variables

View Source
var ErrDaemonDidNotStart = errors.New("the loom daemon did not start")

ErrDaemonDidNotStart is matched by a rejoin's error when the daemon it started exited before it served: after maxSpawnFails of them in a row the TUI stops starting daemons and waits for one (ctrl+r tries again).

View Source
var ErrDaemonNewer = errors.New("the loom daemon is newer than this loom")

ErrDaemonNewer is matched by a rejoin's error when the daemon now running is a newer build than this loom (a newer loom replaced it): the TUI exits, and Run returns that error, for main to say so once the terminal is restored.

Functions

func Run

func Run(ctx context.Context, client *rpc.Client, rejoin Rejoin, startupName string, appConfig *config.Config, program string, pendingDir string, noScripts bool) error

Run starts the Bubble Tea program over client, a connection to the loom daemon, and blocks until the user quits, ctx is cancelled, or a rejoin finds a newer daemon (ErrDaemonNewer). Losing the daemon is not the end: the TUI shows its banner, keeps what needs no model, and joins a daemon again through rejoin (see link.go). It installs a shutdown hook that drains suspended Lua coroutines, closes the client it holds when the program has stopped (the last one it joined), and swallows no errors: any other non-nil return means tea.Program.Run failed.

Parameters:

  • client is the daemon's client, connected and handshaken; Run owns it from here on, and closes it (or the client a rejoin replaced it with) on return.
  • rejoin joins a daemon again once the TUI lost this one (nil: the TUI stays offline).
  • startupName names the workspace the TUI starts on ("": the global one).
  • appConfig is the pre-loaded config from the resolved workspace dir, read for its theme.
  • program is the agent command this TUI's new instances default to.
  • pendingDir is an optional directory to seed the new-instance overlay with (used by `loom` invoked from a non-workspace dir).
  • noScripts disables loading user scripts from ~/.loom/scripts; embedded defaults still load so core keybindings work.

Types

type Rejoin added in v0.14.0

type Rejoin func(spawn bool, say func(string)) (*rpc.Client, error)

Rejoin connects to a daemon again: the startup join, quiet. spawn lets it start one; say reports progress (a replacement) for the banner. A newer daemon's error matches ErrDaemonNewer, and one it started that did not start ErrDaemonDidNotStart.

Jump to

Keyboard shortcuts

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