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.goowns thehomemodel and itsUpdate/View(Model-View-Update).home.Updateis a thin wrapper: it runs the message switch (update), thendrainCore(app/core_glue.go), which empties the client withcore.Core.Sync, thenpublishSelection, which tells the model the selected row (SetSelected) when it moved.- Keys route in two stages:
handleKeyPressdispatches bym.stateto a per-state handler inapp/state_*.go; in the default state, keys flow through the Lua engine viaapp_scripts.go'sdispatchScript, which consultsscript.Engine.HasActionand returns a Cmd that drains the resultingscriptDoneMsg. The keymap isscript/defaults.lua; user scripts in~/.loom/scripts/*.luarebind or add keys. - The TUI holds the daemon's client as
home.core(acore.Core, in production anrpc.Client) and, for the link's state and wakes, ashome.conn(the*rpc.Client; nil in bare test homes, which skip every link check), with its closerhome.stopCore.Rundefers the close as a closure (defer func() { h.stopCore() }()), because a rejoin replaces the client and its closer. AforwardWakesgoroutine per client turns each coalesced wake into acoreWakeMsg:Runstarts the first,resyncone for each client a rejoin brings. It never blocks the client's reader or the model's loop, sincep.Sendwaits for Update. Syncnever leaves the client. It returns the state events for what changed since the lastSync(WorkspacesChanged,ModelChanged,AccountsChanged,GitHubChanged, then each changed workspace'sViewsChanged, coalesced to the newest), then the other events in arrival order;applyCoreEventapplies each.app/core_glue.gois the seam:coreWakeMsg/forwardWakescarry the wakes,drainCore/applyCoreEventapply events,publishSelectiontells the model the selection,newSlotViewbuilds a slot over a workspace's view, andslotForfinds the slot showing aWorkspaceID.- 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 inhome.exitErr, whichRunreturns andmain.goreports once the terminal is restored). Saves are the daemon's:handleQuitflushes 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.gobeforeRun): the full-screen attach buildstmux.NewSessionNamed(name, program), and the liveness guards callm.sessionAlive(name)(a has-session probe; tests set itsaliveProbeseam). Its own environment still decides what it starts itself: the terminal pane's shells (theirupdate-environmentvariables), a relative or~ctx:new_instance{path=…}, which it makes absolute (scriptPath) before theCreate, and a login from the Accounts screen.
The link to the daemon (link.go)
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
Errmatchescore.ErrUnavailable). The TUI polls for a daemon once a second (waitPoll, a rejoin that never spawns) and starts none itself;ctrl+rstarts 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; aftermaxSpawnFails(3) daemons that did not start (ErrDaemonDidNotStart, a daemon that exited before serving) or did not stay up (a rejoined link lost withinstableLink, 30s, of coming up:link.upAt, read through thehome.nowclock seam), it drops to waiting. Only a link that stayed up 30s, orctrl+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
Synccarries its snapshot, which the appliers apply: rows, workspaces, accounts and GitHub state. Rows keep their selection because anInstanceIDnames 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), andOpens 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,mutateUIPrefsandpersistFocusedWorkspaceapply 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. Everyrpc:localquery incore/iface.goreads 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 innewLaunchOptionsOverlay) see a request's effect with no extra round trip. A cast gives no such guarantee.m.corelocks 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 inapp/,ui/orscript/ofsession.Instance, its constructors or options,session.Storage, the launch toggles' setters,core.Workspace,core.Model,core.New,core.Loop,core.Startorcore.Job,config.WorkspaceRegistry/LoadWorkspaceRegistry,config.AppState/State/LoadStateFromorconfig.SaveConfigTo, oraccount.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 callsRegister.
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 bycore.WorkspaceID.homeembeds*workspaceSlot, the focused slot, som.id,m.info,m.list,m.splitPane,m.workbenchand 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 noi == m.focusedSlotbranch 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 forloom <dir>or--workspace),home.failedOpen(saved tabs that failed to open, kept in the open list) andhome.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 inm.slots), showing the startup workspace or, onceenterGlobalModeran, the global one; never nil, and every slot has asplitPaneandworkbench. Only a bare test home shows no workspace (m.id == 0). - Transitions (
app/workspaces.go,app/app_init.go), each showing a workspace throughCore.Openand 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;stayInGlobalModefor 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, thenopenTab, or global mode when the directory is the global workspace's).openListis the tabs in order, thenfailedOpen;persistOpenListwrites it throughCore.PersistOpenList. servedIDfinds a served workspace by name inCore.Workspaces, after aReloadRegistryfor 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, onWorkspacesChanged).closeUnservedLivecloses 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'sresynccloses them itself.renameShownfollows a workspace renamed by ID (home.servedNamesholds the last names; a rename keeps the ID): the tab bar and each rail's header are redrawn and a saved tab infailedOpentakes the new name. - A workspace registered at
$HOMEshares 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
failedOpenand 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,
enterGlobalModedropping the tabs or a classic workspace slot) returnsprunePanesandreleaseSlotCmd, which detaches the attach clients its terminal pane holds onloom_term_*shells (TerminalPane.DetachAll; the paneenterGlobalModecarries into the global slot keeps only the clients of sessions the global list holds,DetachExcept), and the caller runsinstanceChanged. - Each slot caches its workspace's
core.WorkspaceView(slot.info: name and paths, aconfig.Settingscopy, UI prefs, help screens, storage flags, load error, recovery summary), replaced by eachWorkspacesChangedand reread bysyncWorkspacesafter the TUI's own write. UI prefs (mutateUIPrefs) and help screens areSetUIPrefs/SetHelpScreensSeenrequests; the view mode persists per workspace instate.json'suiblock. - The settings overlay edits a
config.Configof the TUI's own (m.settingsEdit, built byconfig.FromSettings), each change sent back whole asSaveSettings; a saved default program becomeshome.program. A theme or default program another TUI saved for the focused workspace applies when itsWorkspacesChangedarrives (applySettingsChange,app/state_settings.go: the theme painted,home.programreplaced), 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 fromcore.Core.Views(the client's replica) when the slot is built (seedViews), replaced wholesale by eachViewsChanged, and reread bysyncViewswhere an Update reads back a change its own request just made. - Every reader sees the store through
rowsOf(the rail'sui.InstanceSourceisslotRows), which copies each row, lays the TUI's own overlays over it (overlay(): the bells ofhome.bells, set by a pane's bell and cleared by focus, and the ladder's scraped status inhome.ladder) and appends the creation flow's draft row. findRow/viewByID/viewBySessionlook a row up across every open slot,activeViewslists the active ones,refreshSelectionrepoints the split pane's and menu's copies (SetInstance) at the selected row on every store or overlay change (the focused slot'sViewsChanged,setLadder,newDraft/discardDraft,createReplied), and theViewsChangedapplier runspruneBells/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 untilconfirmDraftsendscore.Model.Create, and every cancel path callsdiscardDraft(discardPendingLaunchOptionsCancelincluded).
Requests and completions
app/requests.gois the request book:newReqrecords what a request with acore.ReqIDwaits on (pendingCreate,pendingSend,pendingOp,pendingScript,pendingIssue) andhandleReplyroutes itsReply. Every lifecycle request the user starts carries one (opReq, apendingOp), so thatrefusal()can show a refusal throughhandleError.- A prompt send holds input to its instance until its Reply (
sendPrompt,holdInput,m.sending); meanwhilesendingTorefuses inline attach and another send to it with an info line. app/completions.gokeeps 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.Reqnon-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".applyRecoveredselects 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 emitsStartedonly 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 throughm.panes.For(v)(ui.Pane, for a viewv). A client is keyed by the view'sTmuxSession, and its adapter (trust-prompt and pending-prompt patterns) comes from the view'sSessionProgram(inst.Pane().SessionProgram()on the model side), neverProgram. 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:ensureSlotPanesat every workspace load;replacePanewhen a start, resume or recover lands in a loaded slot (core.Started,core.SessionLaunched,core.Recovered, a Luainst:resume()included) and after a workspace terminal's auto-restart (core.SessionLaunched), since the old client watched the replaced session;ensurePanefor the repair after the health tick's probe and afterVerifyDead, both oncore.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, whichRetains the active rows' session names and hands every other client toreleaseClientsCmd, 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, oncore.ClientsStale(a kill or pause completing,KillResult/PauseResult, or anOpFailed) and at every slot drop.Instance.KillandPauseend 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 fullpumpWaitTimeout(signalPumpStop's deadline can't cut the read short), while a dead session's closes at once;releaseClientsCmdcloses its clients in parallel. Full-screen attach (startFullScreenAttachMsg) still runsPausePreviewon 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
paneDirtyMsgfrom the output pump, status transitions ridepaneQuietMsg, andptyDeadMsgrunsVerifyDead's probe. The events (events.go, handled inupdate) report to the model by the ID of the row their session name resolves to (viewBySession):paneDirtyMsgcallsMarkOutput(by session name: the dirty set the next probe takes,takeDirty) andPaneOutput, andpaneQuietMsgcallsPaneQuiet; 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'sSetSelectedinto 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, whoseHealthResultdeliverHealthapplies (applyLivenesspauses the dead and relaunches a dead workspace terminal under its circuit breaker,maxWorkspaceTerminalRestartFailures; an instance a kill, pause or resume moved to Deleting orLoadingwhile the probe ran failsstatusEligibleand is skipped, liveness included); it dispatches the gated jobs that are due and statsaccounts.json(maybeReloadAccounts). The loop re-arms it when the probe lands, so ticks never overlap a probe. The TUI's half (thetickUpdateMetadataMessagecase inapp.go, on its owntickUpdateMetadataCmd) expires toasts, prunes pane clients, runs the inline-attach backstop, the snapshot path's status scan (snapshotScan→snapshotStatusMsg) and the workbench scan;core.HealthCheckedre-arms nothing here (it refreshes the workbench's diff tab). UnderLOOM_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 (
statusDetectedMsgon the event path,snapshotStatusMsgon the snapshot path,paneDirtyMsg's Ready→Running promotion) writes onlym.ladder[id](setLadder: a status and since when), whichoverlay()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), whichstate.jsonsaves; 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 tom.state: overlays and per-state handlers work unchanged on top of it.tabtoggles focus and overview;enter/escreturn to focus;n/Ndrop to focus first. - Overview spans the open workspaces only, one card group each, with a global cursor (
home.overviewCursor, translated toui.OverviewCursorinoverviewData).state_default.gogates script dispatch throughoverviewKeyAllowed, mouse events are dropped, and bell and attention badges clear only on entering focus. Cursor-committing keys go throughfocusCursorSlot()(loadSlot, then select), soenter,D,randnreuse focus mode's intents on the right workspace. - Workbench mode (
app/workbench.go) reuses the focus split for its left half:viewWorkbenchforce-hides the split's terminal (restored fromwbPrevTerminalHiddenbycleanupWorkbench, the single teardown, whichleaveFocusedSlotcalls) and shares itsTerminalPanewith the right panel throughSplitPane.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, andqreturns to the tab the review was opened from (home.wbReviewPrevTab). Persistence runs as Cmds deliveringreviewui.SavedMsg(non-fatal, shown in the footer). The pane claims only the keys it acts on (reviewui.claimsIdleKey), so idleesc, session ops, workspace navigation and, in doc mode, the panel-tab digits fall through to the workbench.home.wbReview(the concrete*reviewui.Pane) and theWorkbench.SetReviewinterface field stay in lockstep;Workbench.SetSessiondrops its half on a title change, so every retarget goes throughhome.dropReviewPane(instanceChanged's workbench retarget does). The wheel feeds the pane synthetic cursor keys (reviewScrollKey).
Keys, modal states and mouse
handleMenuHighlightingdefers 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 nextKeyPressMsgis 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 enumeratedKeyNamevalues andkeys.GlobalkeyBindings, which drive the help panel and menu highlighting only; dispatch is the engine's, andTestKeymapParity(app/keymap_parity_test.go) keeps the table in step withscript/defaults.lua.ctrl+cis 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 instateDefaultandstateInlineAttach, 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 bytea.SetClipboard(OSC 52, which tunnels over SSH) with a local fallback (app/clipboard.go). Interact mode exits onctrl+qor a doubleesc(home.lastEscAt); a singleescreaches 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 ¶
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 ¶
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).
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 ¶
Source Files
¶
- accounts.go
- app.go
- app_init.go
- app_scripts.go
- clipboard.go
- completions.go
- core_glue.go
- doc.go
- drafts.go
- events.go
- help.go
- intents.go
- interact.go
- keybytes.go
- link.go
- overlay_host.go
- overview.go
- panes.go
- remote_control.go
- requests.go
- state_confirm.go
- state_default.go
- state_file_explorer.go
- state_inline_attach.go
- state_issue_picker.go
- state_launch_options.go
- state_mergepicker.go
- state_new.go
- state_prompt.go
- state_quick_interact.go
- state_settings.go
- state_workspace_picker.go
- views.go
- workbench.go
- workspaces.go