core

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: 29 Imported by: 0

README

core

The session model (core/): everything that acts on sessions without a terminal. core.Model serves every registered workspace to any number of clients. In production it runs in the daemon (loom serve, internal/daemon/) on a core.Loop, served over a unix socket by core/rpc/; the TUI holds an rpc.Client as its core.Core. core imports nothing of the TUI.

Files

File Holds
model.go core.Model, Deliver (routes every job result by type; an unknown one is logged as deliver.unknown_result and dropped), the outbox, emit, spawn, spawnBackground, takeJobsSplit, Drain, Begin
workspace.go core.Workspace: context, storage, config, app state, ordered instances (edited only through the unexported add/remove/replace, by identity), recovery summary, loadErr, opened
workspaces.go Loaded, activeInstances, holding, the registry writes Register, Unregister, RenameWorkspace, SetLastUsed, PersistOpenList, and what applies the registry to the served set (serveRegistry, applyRegistry, unload, drop, renameWS, busy)
reset.go ResetWorkspace (the reset steps, which loom reset also runs directly), Model.Reset, deliverReset
launch_watch.go the launch watch: watchLaunch, launchWatchJob, deliverLaunchWatched
load.go Boot, boot, loadWS, ensureLoaded, globalWS, retryLoad, open, ensureTerminal, settleTerminal, maybeSettleTerminals, sweepOrphans, reconcileOrphans, claimTitles
persist.go Persistable, saveWS, saveUnprompted, SaveForQuit, quitSkipsSave
requests.go every lifecycle request, admit, precondition, track, deliverTracked
new_session.go what a client checks before a Create (CheckRoom, CheckWritable, CheckNewTitle, CheckPreservedTitle) and the account the Session Launch Options modal pre-fills (ChooseLaunchAccount, RemovedAccountNotice): one source for the TUI's creation flows and loom session new
ops.go the lifecycle operations behind the requests: killInst, pauseInst, startInst, startOwner, sendInitialPrompt, saveSnapshot, recoverInst (the instance-pointer API across these files is unexported)
completions.go applying the lifecycle jobs' results: deliverStart, deliverResume, deliverRecover, deliverKill, deliverPause, deliverOpFailed, killUnstarted, removeEverywhere, owningWorkspace
tick.go the health tick's model half: Tick, tickInst, probeJob, deliverHealth, applyLiveness, pauseGone, takeDirty, tickInterval
gate.go pollGate, gateIntervals, dispatchGated, gatedResult, deliverGated, redispatch
claude_status.go the roster query (maybeRosterQuery, rosterQueryJob, deliverRoster, rosterStatusFor, observeRoster), adoptClaudeStatus, applyClaudeStatus, statusEligible, maybeRosterQuerySoon
hook_scan.go maybeHookScan, HookTick, deliverHookScan
github.go the GitHub poller (maybeGHQuery, ghPollJob, deliverGH, openedRepos, ghRepoKey, baseBranchByRepo), ExpediteGitHub, WatchGitHub
accounts.go, usage.go the account registry, auth, sync and reload (InitAccounts, ReloadAccounts, maybeReloadAccounts, publishAccounts, accountsRefreshJob), usage probes (maybeUsageProbe, deliverUsage)
claude_tmp.go requestClaudeTmpSweep, maybeClaudeTmpSweep
settings.go SaveSettings, SetUIPrefs, SetHelpScreensSeen
view.go, views.go core.InstanceView; idOf, viewOf, Views(id)/View(id), cloneViews, syncEvents
workspace_view.go, workspace_views.go, workspace_requests.go core.WorkspaceView, wsIDOf, publishWorkspaces, the workspace requests
state_views.go, state_publish.go ModelView, AccountsView, GitHubView, WorkspacesView; publishState, Snapshot
events.go, events_json.go, wire_error.go every core.Event, EventTypes(), the JSON forms of Notice and Reply, core.WireError
iface.go core.Core, the wire's source
loop.go, loop_core.go core.Loop (the health tick's timer and the hook timer) and its Core forwarders
seams.go the test-only exports (…ForTest); the model's own (NewForTest, SetWorkspacesForTest, SetExecForTest, SetRegistryForTest) are in model.go

Workspaces and boot

Model.workspaces holds every served workspace, each loaded once and dropped only when it leaves the registry (Unregister, or a reread that no longer names it: applyRegistry). Tests reach a workspace's instances through AddForTest/RemoveForTest/InstancesForTest.

Model.Boot runs once, in the daemon (daemon.Serve), after it takes the lock and before the loop starts; it is not in Core. It runs InitAccounts, detects the default account's remote-control auth when the global config enables remote control or an extra account exists (following the global config's setting, not the startup workspace's), and runs boot: it loads the global workspace (globalWS) and every registered one (ensureLoaded), one per config dir. wsByConfigDir compares canonical paths (canonicalDir, through session.CanonicalPath), so a renamed registry entry, the startup context, or a second entry reaching the same directory through a symlink is the same workspace, served once under the name it was first served by: serving one directory twice would let a stale copy's save overwrite the other's. Then one orphan sweep runs over them all (sweepOrphans). Boot returns its notices, which the server keeps for the first client. A workspace registered later is served from its Register, or from the ReloadRegistry that finds it (every TUI's startHome runs one); one unregistered stays served until the daemon restarts.

loadWS is the one load path: applySessionConfig, LoadAndReconcile, the crash-restart of every session the reconcile found dead with its worktree intact (crashRestart), except the workspace terminal's, which waits for the workspace's first open, then reconcileOrphans. Loading every workspace leans on the ownership checks in ../session/README.md (SessionHome, startedElsewhere, HeldElsewhere): tmux names are per server, not per workspace. Instance.Kill (and so a discard, which kills a Recoverable entry) and Instance.Resume ask HeldElsewhere of the session under the record's name (Instance.sessionHeldElsewhere, session/reconcile.go; core/held_name_test.go).

Session flags per config dir. The loom-context and subagent-tracking launch toggles live in session keyed by config dir (dirFlags); syncSessionFlags sets a workspace's at its load and on SaveSettings, and a launch reads its own instance's.

Opening a workspace

A client showing a workspace, as a tab or as the workspace it shows while none is open, calls Open(id) (open). The first open since the model started sets opened, which gates the workspace's terminal and its GitHub polling, and expedites the GitHub poll. Which workspaces a client shows is the client's own state: an open publishes nothing tab-like, and nothing in the model closes a tab.

ensureTerminal creates the workspace terminal, killing a leftover session under its title only when the sweep's ownership test proves it this workspace's (session.KillOwnedTmuxSession). For one that died while nobody had the workspace open (CrashRecovered) or is Paused (its restart breaker stopped it, or reconcile found its name held), it asks session.HeldElsewhere and hands the answer to settleTerminal:

  • held: the other session is left running and the terminal stays, or is marked, Paused;
  • free: it relaunches the terminal (crashRestart, or ResetRestartFailures then Restart);
  • unanswered: nothing changes or is saved, the workspace is marked terminalUnsettled, and the health tick asks again off the model's goroutine (maybeSettleTerminals: one background job per workspace, one check in flight, asked again after every unanswered one, delivered as terminalChecked; an answer about a terminal killed meanwhile settles nothing, TestSettleTerminals_…) until tmux answers.

ensureTerminal saves the workspace after it creates, relaunches or pauses the terminal (saveTerminal), so a crash before the next save can't leave a live terminal with no record, which the next first open would kill and recreate, losing its conversation. Until the first open the terminal is dormant: activeInstances leaves it out, so the tick neither probes, relaunches nor pauses it.

Unregistering, renaming and resetting

Unregister(name) saves the workspace (saveForUnload), removes the registry entry and stops serving it (drop). Its tmux sessions are untouched, and registering the directory again serves them under the same IDs, which derive from the disk. It is refused (ErrRefused) for the global workspace, an unknown name, a workspace with a Loading or Deleting session and a workspace with a reset running (busy). An entry that is a twin of one still registered only leaves the registry. RenameWorkspace(from, to) renames the registry entry, whose open list and last-used workspace follow, and the served workspace in place (renameWS: a renamed copy of its context, the same ID, its terminal's title unchanged); it refuses the global workspace, an unknown from and a to already registered. ReloadRegistry applies the same two changes for a registry edited elsewhere (serveRegistry, applyRegistry); a busy workspace stays served until the next reread (workspace.unload_deferred). Tests: core/unregister_test.go.

Reset(id, req) drops the served workspace's instances at once and runs resetWorkspace as a tracked job, which deletes the records, sweeps the tmux sessions started in the workspace's roots and removes its worktrees and branches; loom reset with no daemon runs the same steps over the records on disk (ResetWorkspace). It is refused for an unknown workspace, a busy one, a reset already running and a workspace whose load failed. While it runs the workspace takes no Create and no terminal (resetting); deliverReset serves the records again if nothing was deleted, and gives an opened workspace a fresh terminal. The Reply carries the job's error. Tests: core/reset_test.go.

RemoveAccount(name, force) removes an account; without force it refuses while a session uses it or its dir holds unshared files, and force overrides both and logs it.

Failed loads

loadWS leaves a workspace whose load failed served, empty, with its storage's write latch engaged, and records loadErr (published as WorkspaceView.LoadErr; the boot only logs it, workspace.load_failed). The TUI goes by its own failed opens (failedOpen), not LoadErr, so a failed workspace not in the open list shows nowhere until something opens it. sweepOrphans leaves its roots out of the owned set, its titles being unknown, and still sweeps every other workspace. Every Open retries it (retryLoad, which rebuilds its state, config and storage from disk, since a storage keeps the payload it was built over) and returns the error while it still fails.

The TUI's side (Workspace.loadErr reaches it only as LoadErr): a classic startup on a failed workspace exits with the error. A saved tab that fails to open at startup (restoreSavedWorkspaces) stays in the open list the TUI persists (home.failedOpen, appended by openList) and shows checked in the picker, labelled "(failed to load)", so later launches retry it, until it opens (openTab) or the user deselects it (applyWorkspaceToggle); global mode (enterGlobalMode, or stayInGlobalMode for a Global commit made from global mode) closes them all. When every restored tab fails, the classic slot opens the startup workspace instead; if that fails too, the error is shown rather than exiting, the latch refuses every save (the daemon's stop skips it: core.Model.SaveForQuit, quitSkipsSave), and handleQuit keeps the failed tabs in the open list. Those skips are lossless because new sessions are refused while the focused storage WritesRefused() (latchedStorageErr), so a latched list stays empty.

Requests, replies and causes

Every lifecycle action is a request, by ID where it names an instance, with an optional ReqID (core/requests.go): Kill, Pause, Resume, ResumeWith (the R flow: the new launch options applied, then a resume), Recover, Merge, Push, SendPrompt, Create(ws, NewInstance, req) (builds and adds an instance and, with Start, configures and starts it) and FetchIssue. A non-zero ReqID is answered by a Reply (Req, ID, Err, Notice, Issue): at once for a refusal or a Create, otherwise when the request's job lands (track, deliverTracked).

Each request that names an instance first runs admit (Create, which names a workspace, refuses one no longer served instead): a served workspace must hold the ID (else ErrNoSession), and the instance must pass precondition, which mirrors the keys' gates in app/intents.go (a gate that needs a pane, such as the send's liveness check, stays in the TUI) (no kill, pause or push of a workspace terminal or a busy session, no resume of one not Paused, …). A refusal's error matches core.ErrRefused (ErrNoSession does too); with ReqID 0 it is only logged (request.refused). A failed job is not a refusal: the model has already shown it as a Notice, and the Reply's Err carries it too.

The pane triggers name instances by ID as well (SetSelected, PaneOutput, PaneQuiet, VerifyDead); MarkOutput takes the session name.

The request is ambient (Model.cause). While the model applies a request's job result (a caused result, which Deliver unwraps through causedBy, or a tracked one), the Started, Recovered and Notice events it emits carry the request in Req (emit stamps them), and the jobs it spawns meanwhile serve the request too (spawn wraps their results as caused). So a chain's last event (Create, then the start, then the initial prompt's send, then Started) still names it. The model's own jobs (the tick's probe, gated jobs, dead checks) go through spawnBackground and never inherit it. The loop takes the two kinds apart (takeJobsSplit) and counts the foreground ones until they land: Loop.Quiesce, the daemon's stop, fires no more ticks, waits for those (the daemon allows Options.QuiesceTimeout) and leaves the background ones to be dropped at Stop, so a pause or kill is never cut off mid-step.

The selection is a set (Model.selected): SetSelection names every client's selected row at once (SetSelected names one), and the tick's probe refreshes the full diff of each (selectedInstances).

Completions

Completions (core/completions.go) act on the *session.Instance they carry: a failed start (a StartResult with an error) removes its instance from its owner's workspace and kills that instance (killUnstarted), a KillResult removes its instance from every served workspace (removeEverywhere), and an OpFailed reverts the instance it carries (and emits Reactivated). Results that need a workspace carry the owner stamped at dispatch on the model's goroutine: core.StartResult.Owner and ResumeResult.Owner (from startOwner, the served workspace holding the instance; the workspace the caller passes is only the fallback) and RecoverResult.Owner (the workspace holding the placeholder, found by the Recover request's lookup). deliverStart, deliverResume and deliverRecover resolve the owner (owningWorkspace), act on its instances and storage (saveWS; the owner is always served, since the model never drops a workspace), and report through events (Started, Recovered, SessionLaunched, …) stamped with their cause. A pause saves inside its job, so PauseResult only asks for a prune. A job that needs the owner's storage captures it when the model builds it (killInst, pauseInst, saveSnapshot in core/ops.go). An N flow's initial prompt is sent by a job after the start lands (sendInitialPrompt), and Started is emitted only once that send returns (deliverPromptSent), so a client's inline attach, which forwards keys to the agent, begins only after the prompt is in.

The model has no focus. Where an operation needs a workspace the user chose (Create's, also the start's fallback owner) the caller passes it, an ID request finds its workspace by lookup, and whatever depends on focus or m.state (the selection, inline attach, the "started in X" wording, the stateDefault guard) stays in the TUI's event appliers.

Instances and workspaces as values

Clients see an instance only as a core.InstanceView (view.go): everything the TUI renders or gates a key on (Active() is the active-instance rule; WorktreeRepoPath is what Lua's worktree handle is built on) and nothing that acts. It names its instance by a core.InstanceID, which idOf derives from the record (its workspace's canonical config dir, its title and created_at), so every daemon over one disk agrees; 0 is never assigned (the TUI's draft row uses it). Views(id)/View(id) (views.go) build views of served workspaces only.

A workspace crosses as a core.WorkspaceID (wsIDOf, a hash of its canonical config dir, so every daemon over one disk agrees and a tab closed and reopened shows the same one) and a core.WorkspaceView (workspace_view.go; LoadErr is the text of a failed load, "" once it loaded), answered by Workspaces() (every served workspace, in serve order) and Workspace(id). The workspace requests take and return IDs and views (workspace_requests.go: Workspaces, Open, Views, Create, IsLoaded, Registry, ReloadRegistry). Started/Recovered name their owner by ID with its label.

SaveSettings (settings.go) replaces a workspace's settings, writes its config.json and applies the change at once: that workspace's launch toggles in session, and, for the global workspace only, the program the accounts' Claude commands run with (Options.Program, the global config's in the daemon, then the global workspace's last saved default program). The program a client's drafts default to is the client's own (home.program in the TUI). SetUIPrefs and SetHelpScreensSeen write its state.json.

Registry() is a RegistryView copy (the registered workspaces, the open list, LastUsed). ReloadRegistry rereads the registry, serves any workspace registered since, and applies removals and renames made since (a hand edit of workspaces.json included). The registry's writes are Register (which returns the new workspace's view, for the client to Open), SetLastUsed and PersistOpenList (the open list a client hands it, its tabs then the ones it failed to open: the model only writes it, and never acts on it). AccountNames() is all the TUI sees of the account registry. Every query hands out copies (GitHubSnapshot, AccountUsage, AccountSync, the views; core/copies_test.go).

Publishing state

Sync (syncEvents) publishes by diffing, in a fixed order and ahead of every other event: one WorkspacesChanged carrying every served workspace's view whenever any changed (publishWorkspaces, workspace_views.go), then publishState's events (state_publish.go), then a ViewsChanged for each served workspace whose views changed since the last publish, carrying deep copies (cloneViews). It also forgets the IDs of instances no served workspace holds.

publishState emits three events, each carrying a state view of state_views.go (the fourth, WorkspacesView, is the workspace views):

  • ModelChanged (ModelView: the default account's remote-control auth and the registry);
  • AccountsChanged (AccountsView: the names, the loaded and extra flags, the Claude program, the accounts, their auth, link reports and usage, the probes' errors, CredentialOverride and RunningAsAccount);
  • GitHubChanged (GitHubView: the snapshots, the poll errors, the aliases and gh's availability).

The model and account views are diffed whole (reflect.DeepEqual). The views' Clone methods deep-copy their slices and keep every other field (a ModelView.Clone that rebuilt the RegistryView once lost LastUsed, so every replica's restore focused the first tab). The account view is also republished after every usage probe round (usageGen, bumped in deliverUsage), since the TUI renders a sample's age; the GitHub view, whose snapshots can be large, is republished whenever a poll lands (ghGen, bumped in deliverGH, the one place its state changes). Nothing emits AccountsChanged or GitHubChanged by hand.

Model.Snapshot is the whole published state as events, in Sync's order, and leaves the diff baseline alone. Loop.SyncAndSnapshot (not in Core) runs a Sync and a Snapshot in one loop call, so a client that connects starts from exactly the state the next Sync diffs against.

The state views' methods replicate the logic of the model's own queries, which stay as they are because several run on every tick. Parity is tested twice: TestStateViews_AnswerAsTheModel and TestWorkspacesView_AnswersAsTheModel (core/state_views_test.go) compare view and model directly, and TestReplica_AnswersAsTheModel (core/rpc) compares the client with the loop over the wire, misses included.

Core, the loop and jobs

core.Core (iface.go) lists every method the TUI calls, and home.core has that type. *Loop implements it in process (loop.go, with every forwarder in loop_core.go, each checked by TestLoopForwardsEachMethodToItsNamesake); *rpc.Client implements it over a connection. iface.go is also the wire's source: the wire code is generated from it, and its parameter names are the wire's field names (auth, settings, prefs, program, number, workspace). A method's line comment says how a client serves it: // rpc:local is answered from the client's replica; // rpc:cast is sent one way, with no reply, and the server publishes nothing after one; // rpc:client (Sync) never leaves the client; every other method is a request, whose reply follows the events it produced. CredentialOverride and RunningAsAccount are local; WatchGitHub is a cast. Not in Core: Boot, InitAccounts, SetRCAuth, Begin, SyncAndSnapshot, SetSelection. SaveForQuit is still in Core, though only the daemon calls it.

Core is value-typed: TestCoreIsValueTyped (core/value_boundary_test.go) walks every method and every Event (EventTypes(), the production list the wire names and decodes events by, kept complete by TestAllEventsListsEveryEvent) by reflection and fails on anything but plain data (no func or chan, no interface but error and Event, no sync type, none of the model's own objects).

Model is single-goroutine, and its Loop runs it: the loop serves each call as a round trip, starts the jobs the model queued (takeJobs, after every step) on goroutines of their own, delivers their results on the loop (core.Model.Deliver), fires the health tick from its own timer (tickInterval, armed by Loop.Begin, which whatever serves the loop calls once: daemon.Serve, or rpc.InProcess in tests; re-armed only when the probe's HealthResult lands, so probes never overlap) and the hook timer (hookInterval, 250ms, re-armed after each tick), and signals Loop.Wakes after anything it did unprompted, except a step that changed nothing a client sees (Model.noWake). A panic on the loop's goroutine or in a job is a core.LoopPanic; the loop keeps the LoopPanic, and every later call re-raises it (the model's state is unknown after one). Quiesce readies a stop, and Stop ends the loop: later results are dropped and later calls run nothing.

Blocking work is a core.Job (func() any) that reads no model state; Deliver routes its result by type. Every job goes to the outbox, which the loop empties after every step; the Events wait there until the server's Sync publishes them, after every request and on every wake.

The health tick and gated jobs

core.Model.Tick (tick.go) fires from the loop's timer, favouring every client's selected row, and queues one probe job over every active instance of every served workspace, an unopened workspace's dormant terminal excepted (tmux liveness, parity, diff stats: probeJob). deliverHealth applies its HealthResult: applyLiveness pauses the dead (pauseGone, saved through saveUnprompted) and relaunches a dead workspace terminal under its circuit breaker (maxWorkspaceTerminalRestartFailures); Claude's reported status is adopted; an instance a kill, pause or resume moved to Deleting or Loading while the probe ran fails statusEligible and is skipped entirely. MarkOutput fills the dirty set the next probe takes (takeDirty) to gate diff refreshes, and core.HealthChecked is emitted when the probe's result lands.

The tick also dispatches the gated jobs that are due (roster, hook scan, GitHub poll, usage probe, the Claude temp-dir sweeps workspace loads queued) and stats accounts.json for a change (maybeReloadAccounts). Every throttled background job goes through a pollGate (gate.go; intervals in gateIntervals, keyed by kind, so even a zero-value core.Model is throttled): dispatchGated arms the gate only when its builder returns a core.Job, and wraps the result in a gatedResult that Deliver disarms (deliverGated) before routing the inner result to its handler. A request() made while a dispatch is in flight dispatches the job once more after that flight lands (redispatch). Adding one: ../docs/claude/adding-a-gated-job.md.

Claude status and the roster

session/claude_roster.go shells out to claude agents --json. rosterQueryJob (claude_status.go) runs it off the model's goroutine on its own cadence: maybeRosterQuery throttles by rosterInterval and guards against overlap through gateRoster (core/claude_status.go), because the snapshot path's faster tick would otherwise keep a claude process alive much of the time, and stack concurrent ones if the CLI hung. The roster covers ordinary interactive sessions, not just claude --bg ones, keyed by cwd. The model's roster field holds the result; rosterStatusFor joins on Instance.GetWorktreePath() and maps busy→Running, waiting→Prompting, idle→Ready. The roster is per config dir (claude agents --json under an empty dir returns []), so rosterQueryJob runs one query per account in use (session.QueryClaudeRosterEnv) and rosterStatusFor joins rosterByAccount[inst.Account()] (the default account's stays in roster); one account's failed query clears only its own entries.

A roster answer is offered to each active Claude instance as it lands (observeRoster), stamped with the query's start time (rosterResult.at), and merges with hook observations, the newest observation winning (session/claude_state.go). Only the model writes a reported status: deliverHealth and applyClaudeStatus (hook scans, roster answers) both go through adoptClaudeStatus, which applies the status and records Instance.WaitReason. The TUI's status paths (statusDetectedMsg on the event path, snapshotStatusMsg on the snapshot path) write no status: they read the row's StatusReported before their content ladder and leave a reported row to the model; an authoritative answer also suppresses maybeRedetect.

rosterStatusFor fails closed, like DetectClaudeRemoteControlAuth: non-Claude agents, an empty or failed query, no entry for the worktree, an ambiguous cwd (dropped in QueryClaudeRoster, logged as session.roster.ambiguous_cwd), a cwd holding only background sessions, and unrecognized status strings all return false from rosterStatusFor (no opinion), and the scraper ladder decides. A failed query clears the roster and turns every roster-sourced observation into no opinion (claudeState.rosterSilent); a hook-sourced one stands. RosterEntry.WaitingFor (Claude's own reason for blocking: "sandbox request", "dialog open", "input needed", "goal proposal", …) rides through adoptClaudeStatus onto the transient Instance.waitReason and replaces the generic phrase in CardData.statusLabel, verbatim and truncated; any non-Prompting or non-authoritative outcome clears it. It is never serialized. Tests: session/claude_roster_test.go, core/claude_status_test.go, core/gate_test.go, app/roster_status_test.go, ui/card_test.go.

Hook scans. maybeHookScan (core/hook_scan.go, gateHookScan) runs on the health tick, on the loop's hook timer (Model.HookTick, every hookInterval, only while an active Claude instance exists, so a daemon with no TUI open reads Claude's hook events within a quarter second), on pane output (core.Model.PaneOutput) and, through pollGate.request(), on pane quiet (PaneQuiet) when Stop and PermissionRequest arrive. A tick and a scan that moved nothing of any instance's view (hookFace) set noWake, so an idle Claude costs no publish four times a second (TestLoop_AnIdleHookScanWakesNoClient, TestDeliverHookScan_NoWakeOnlyWhenNothingMoved). A scan that changes a status applies it at once (applyClaudeStatus) and requests a roster query to confirm it. Answering a prompt fires no hook, so output on a Prompting session queries the roster (maybeRosterQuerySoon, at most every promptingRosterSpacing). A scan naming the conversation a relaunch resumes is saved (deliverHookScan, through saveUnprompted).

Trust prompts: the launch watch

An agent may stop at a trust prompt right after it launches, and only the daemon answers it (no TUI does: a status scan only reads the pane). After every real launch the model calls watchLaunch: a start (deliverStart), a resume that relaunched rather than reattached (ResumeResult.Relaunched, deliverResume), a crash restart at a workspace's load or a terminal's settling (crashRestart), a workspace terminal's creation (ensureTerminal) and its relaunch (settleTerminal, applyLiveness). The watch is a background job (spawnBackground: Quiesce does not wait for it) that builds a lifecycle tmux.Session by name and captures the pane every launchWatchEvery (250ms) for up to launchWatchFor (30s), answering each trust prompt it sees once while the screen shows it (trustAnswer): Claude's MCP prompt can follow its trust prompt, and aider's answered prompt line lingers. A prompt answered as shown gets the adapter's keys (AnswerTrustPrompt); one with a choice (TrustPromptChoice: Claude's safety check, whose menu selects "No, exit" first) is moved down one option per capture, each move waited out until drawn, and gets Enter only once a capture shows its cursor on the choice (SelectedOption, IsOption); a menu that never gets there, or shows no single cursor, is left to the user. It ends early when the session is dead, and otherwise at its deadline, handing the prompt it settled to the watch of a relaunch (launchWatched.settled). One watch runs per tmux session name (Model.watching): a launch while one runs is folded into it and the session is watched afresh when it ends. An agent with no trust prompt to answer (Session.AnswersTrustPrompt) is not watched. Tests: core/launch_watch_test.go, and TestE2E_Clients_TrustPromptAnsweredWithNoTUI end to end.

The GitHub poller

maybeGHQuery (core/github.go) rides the health tick on its own ghInterval cadence through gateGH; the ghAvailable backoff is a pre-check ahead of dispatchGated, and no opened repo means no dispatch. It polls only the repositories of opened workspaces (openedRepos: every workspace a client has opened since the model started), each with its own workspace's base branch. An opened workspace with no repository (the global one) stands for the repositories its sessions run in (Instance.Path), against its own base branch, and with no session it polls nothing. Last come the repositories a client asked for (Core.WatchGitHub, a cast: the issue picker asks on every open and on every GitHubChanged while it stays open, and an N prompt's #n expansion asks for its draft's repository), against the global workspace's base branch, each polled for ghWatchTTL after the last ask (ghWatched; an expired one is dropped at the next ask). An ask the poll has answered already renews the watch without polling at once. Workspaces with a repository of their own come first, deduplicated canonically (canonicalDir), so a global session in a registered repository is polled against that workspace's base branch.

ghPollJob groups the paths by their checkout's top level (git.RepoRoot, git rev-parse --show-toplevel, canonical; a path git can't place stands for itself), so a repository reached through a symlink or a subdirectory is polled once, against the first path's base branch, for the issues every path links. Its results (ghState, ghErrs, ghBases) are keyed by that top level, and each path inside another's is recorded as an alias (ghAliases, published as GitHubView.Aliases); every lookup goes through ghRepoKey (the instance join, parity's base, GitHubSnapshot/GitHubErr on the model and the replica). Each poll resolves and fetches the base ref per repo (git.FetchRef, even without gh) and, when gh is available, runs github.Query. ghState is replaced wholesale, so an errored repo is dropped: its cards render Known=false (nothing), and Known=true, HasPR=false is a real "no PR". Results join onto Instance.SetGitHubState (transient; viewOf copies it into InstanceView.GitHub through GitHubState(), and ui.BuildCardData reads the view's). Ahead/behind (Instance.UpdateParity, one local rev-list) rides probeJob, keyed on ghBases.

core.Model.ExpediteGitHub() makes the next tick poll at once (an in-flight poll still lands first). A successful push (core.Model.Push, applied by deliverPush), an issue-born session (handleIssuePicked; handleIssueExpanded asks WatchGitHub, which expedites too), the issue picker opening on a repo with no snapshot or error yet, and a workspace's first open (Core.Open) all expedite. The TUI reads the poll through GitHubSnapshot/GitHubErr/GitHubUnavailable, answered from its replica, and core.GitHubChanged refreshes an open issue picker. GitHub state never sets NeedsAttention.

ghAvailable.ok latches true: req.check is !checked || !ok, so once CheckCLI succeeds it never re-runs, and gh breaking mid-session surfaces only as per-repo errors. An unavailable result is re-probed every ghRecheckInterval, so gh auth login after the daemon started recovers without a restart. ghPollRequest.configured is a map[string]string keyed by repo path, built by baseBranchByRepo() from each opened workspace's own config.json, since each workspace has its own BaseBranch (the TUI's m.settings() is only the focused slot's). ghPollBudget bounds the whole poll, under ghInterval: github.Query budgets each gh subprocess separately (two list calls plus one issue view per linked closed issue), and one repo with many linked closed issues would otherwise stall every other workspace's refresh. UpdateParity runs in probeJob before the wantFull/ShouldRefreshDiff early return, which skips git for an idle session (tmuxUpdated false), because the base branch moves with no session activity at all.

Both issue fetches are core.Model.FetchIssue requests (a github.View job) whose Reply carries the issue. On the TUI's side (app/state_issue_picker.go) the picker's pick and the N prompt's #n expansion record a pendingIssue holding an issuePickedMsg or issueExpandedMsg, which handleReply fills and hands to handleIssuePicked/handleIssueExpanded. They can land long after the user acted; both drop the result, with an explanation, when msg.repo != m.repoPath() or m.state != stateDefault, because openLaunchOptionsForNew would otherwise replace another flow's pending launch options. handleIssueExpanded also drops a result whose draft is no longer m.draft, and discards the draft whenever a guard fires (issueExpandDropped); it degrades on a fetch error, so its guards run before its err != nil branch.

Accounts and usage

The account registry, auth, sync, usage and reload logic live in core/accounts.go and core/usage.go; the views are the TUI's, refreshed on core.AccountsChanged. maybeReloadAccounts rides the health tick and only stats accounts.json, reloading (core.Model.ReloadAccounts) when its size or mtime moved; every user-paced action that reads the registry (opening Launch Options, opening Settings, an Accounts-screen request) calls ReloadAccounts first. accountsChanged compares a signature (the default, every name=dir, and the load error) against what was last seen (noteAccountsState, also called after the model's own writes), so a no-op reload touches no view and a load error is reported once. Auth is re-read (RequestAccountsRefresh, gateAccountsRefresh, accountsRefreshJob) when a reload finds an account with no auth entry, while the default account's identity is unknown and an extra account exists, or when a usage probe finds an account that had plan access losing it (lostAccess; an expired login probes like API-key auth, Usage.Available=false, until claude auth status re-runs). The refresh re-syncs an existing account only through syncMainDir's guard. publishAccounts hands the registry's dirs to session.SetAccountDirs, which every launch resolves an account name through. The default account's remote-control auth (RCAuth) is detected by Boot and refreshed by the accounts refresh; it is per account (core.Model.RCAuthFor; an extra account not read yet is Unknown). Usage probes (account.ProbeUsage, a headless claude -p answering the SDK's experimental usage request; TestRealClaude_UsageProbe, opt-in, pins its shape) run on gateUsage, expedited when a picker opens; usage is display-only, so a failed probe keeps the last sample. accountUsers counts each loaded workspace's live instances and reads state.json only for config dirs no loaded workspace covers. The model's own environment decides CredentialOverride and RunningAsAccount (noteRunningAsAccount).

Orphans and Claude temp dirs

reconcileOrphans (core/load.go, called from loadWS) auto-cleans stale worktrees and surfaces unsaved or live ones as Recoverable entries. Recoverable is ephemeral: filtered out of core.Persistable, re-derived from disk each load, and inert (EnsureRunning no-ops on it). r recovers (core.Model.Recover: adopt via ReconcileAndRestore); D discards (worktree removed, branch kept, IsExistingBranch). reconcileOrphans also queues a Claude temp-dir sweep (requestClaudeTmpSweep, snapshotting the claim set then; a workspace whose storage failed to load queues none), which the tick (Model.Tick) dispatches on gateClaudeTmp, one in flight (core/claude_tmp.go). A Pause and a Resume of the same worktree refuse each other (core.Model.Resume takes only a Paused instance; a Lua inst:pause()/inst:resume() is the same request), as do two of the same, keyed by the canonical worktree path in opsInFlight.

Wire errors

On the wire an error is a core.WireError{Code, Message} (wire_error.go), which keeps the sentinels clients test with errors.Is. Codes: not_found (ErrNoSession, whose Is also matches ErrRefused), unavailable (ErrUnavailable: the daemon is stopping, or the client has lost it; also a refusal, and never the model's own answer: the stopping server and the client produce it, and the TUI fails its stranded requests with it; an older peer sees only the message), refused (ErrRefused), storage (session.ErrStorageLoadFailed), error (anything else: only its message survives), panic, protocol, mismatch and unsupported (CodeUnsupported: a method the server does not know, an ordinary error so a newer client can probe an older server). ToWire encodes: a WireError passes unchanged, an error wrapping one keeps the inner code with the whole wrapped message, and any other takes the code of the first sentinel it matches. FromWire(nil) is a nil interface, never a typed nil. Notice, Reply (events_json.go) and git.DiffStats (session/git/diff.go) encode their error fields this way; DiffStatsData, the persisted form, does not.

Saving

The daemon saves on requests, after the changes the model makes on its own (saveUnprompted: the tick pausing an agent whose session is gone, pauseGone from applyLiveness; a hook scan naming a conversation, deliverHookScan), and at its stop (SaveForQuit, which saves every served workspace: a failed save of a workspace opened in this run is returned for the daemon to log, the write latch excepted, quitSkipsSave; an unopened one's failure is only logged, quit.save_failed_unopened; one whose config dir is gone is skipped rather than recreated).

Boundaries

TestCoreImportsNoUI (core/boundary_test.go) walks the import graph and fails on app, ui/..., script, keys or a charm.land package reached from core, directly or through another loom package. seams.go and model.go hold the test-only exports, and TestNoProductionCallsOfTestSeams (internal/testenv/seams_enforce_test.go) fails on any production use of one, a call or a reference taken as a value. core/doc.go holds the package comment.

Tests

Core's own tests drive a Model directly, on their goroutine, with Sync (events and jobs), Drain (which publishes no views) and Deliver.

  • NewForTest builds a model with no workspace and no side effects; SetWorkspacesForTest(wss...) installs workspaces, each served and opened, in serve order (the model has not booted, and a Boot loads the global and registered workspaces beside them).
  • core/boot_test.go's workspaceDef and bootModel build a model over registered workspaces laid out on disk (its own global dir, a tmux executor on which every session is dead), which the test then boots; openDef opens one. startForeignSession starts a session holding a title from another directory, standing in for another workspace's or another loom's.
  • CausedForTest delivers a result as a request's job would. Other result types come from seams.go's …ForTest constructors.
  • core/testhelpers_test.go holds the fixtures: storedWorkspace (a workspace over a fresh config dir and storage), newInst, newTerminal, pausedInst, startedInst, gitRepo, pausedWorktreeInst, and isolateTmux(t) (a fresh private tmux server per test, killed when it ends).
  • core/testmain_test.go isolates tmux and ~/.loom for the binary.
  • The loop's seams: StartForTest (a loop that holds every job for JobsForTest and never ticks on its own, TickForTest; idle between calls, so a test may reach its model through ModelForTest), DeliverForTest, SelectedForTest, SetRCAuthForTest, HookTickForTest (the hook timer's tick; a StartForTest loop never fires it on its own).

Documentation

Overview

Package core is loom's session model: the loaded workspaces and their instances, and everything that acts on them without a terminal: loading and saving, reconcile and the sweeps, the lifecycle operations and their completions, the health tick and the background jobs.

Since daemon stage 1E the model runs on a goroutine of its own: a Loop owns it, serves every Core method as a round trip over that goroutine, starts the Jobs the model queues on goroutines of their own and delivers their results on the loop (Deliver), and fires the health tick from its own timer. A Job reads no model state. The model reports to its client (the TUI, package app) through Events, which the client drains (Sync) when the loop wakes it (Loop.Wakes) and after each of its own messages. Core's own tests drive a Model directly, on their own goroutine, with Sync, Drain and Deliver.

core imports nothing of the TUI (TestCoreImportsNoUI): the daemon (loom serve) runs it with no terminal. Focus is the TUI's: where an operation needs "the workspace the user is looking at", the caller passes it.

Index

Constants

View Source
const (
	// CodeNotFound: the request named a session no loaded workspace holds
	// (ErrNoSession).
	CodeNotFound = "not_found"
	// CodeRefused: the model refused the request (ErrRefused).
	CodeRefused = "refused"
	// CodeStorage: the workspace's storage refuses writes
	// (session.ErrStorageLoadFailed).
	CodeStorage = "storage"
	// CodeError: any other failure; only its message survives.
	CodeError = "error"
	// CodePanic: the model panicked (LoopPanic); the client re-raises it.
	CodePanic = "panic"
	// CodeProtocol: a frame the other side could not use. The two sides
	// disagree about the wire, so a client treats it as fatal.
	CodeProtocol = "protocol"
	// CodeUnsupported: the peer does not know the method. An ordinary
	// error, never fatal, so a newer client can probe an older server.
	CodeUnsupported = "unsupported"
	// CodeMismatch: the two sides speak different protocol versions.
	CodeMismatch = "mismatch"
	// CodeUnavailable: the daemon is stopping, or the client has lost it
	// (ErrUnavailable, a refusal). An older peer sees only its message.
	CodeUnavailable = "unavailable"
)

Wire error codes: what a client can still tell about an error once it has crossed a process boundary as text (see WireError).

View Source
const InstanceLimit = 10

InstanceLimit caps the rows a workspace holds (its terminal and recoverable rows count) before a client creates another. It is a soft guardrail: tmux server memory and git worktree overhead are the real bound, so raise it deliberately.

View Source
const MaxTitleWidth = 32

MaxTitleWidth is the widest title, in terminal cells, a new session takes.

Variables

View Source
var ErrNoSession error = refusedError{errors.New("no such session")}

ErrNoSession refuses a request naming an ID no loaded workspace holds: the session was removed, or its workspace closed, after the client last saw it. It matches ErrRefused.

View Source
var ErrRefused = errors.New("request refused")

ErrRefused marks every refusal: a request the model would not start (its session gone, its precondition failed, its transition refused). A Reply's Err matches it (errors.Is) exactly when the request was refused, which the model reports nowhere but in that Reply; a failure of the request's job does not match it, and the model has already shown that one in a Notice.

View Source
var ErrUnavailable error = refusedError{errors.New("the loom daemon is unavailable")}

ErrUnavailable refuses a request the model cannot take: the daemon is stopping, or the client has lost it. It matches ErrRefused, so the TUI's refusal path shows it.

Functions

func AccountsRefreshedForTest

func AccountsRefreshedForTest(defaultAuth *session.RemoteControlAuth, auth map[string]session.RemoteControlAuth, sync map[string]account.SyncReport) any

AccountsRefreshedForTest is a finished accounts refresh, for Deliver: the default account's auth (nil when not reread) and each extra account's auth and link report.

func CausedForTest

func CausedForTest(req ReqID, result any) any

CausedForTest is result as a job serving the request req delivers it: the Started, Recovered and Notice events it produces name req, as when the TUI's own Create or Recover lands. A test that hands the model an operation's result directly wraps it so, or the TUI treats the result as another client's.

func CheckNewTitle

func CheckNewTitle(title string, ws WorkspaceView) error

CheckNewTitle refuses a title a new session in ws can't take: empty, wider than MaxTitleWidth cells, or preserved (CheckPreservedTitle).

func CheckPreservedTitle

func CheckPreservedTitle(title string, ws WorkspaceView) error

CheckPreservedTitle refuses a title that belongs to a record ws's storage preserves on disk but could not load (a reconcile failure, or a newer loom's record after a downgrade). Storage never dedupes against such records, so creating the session would persist a second record under the title, and the two would share a tmux session name.

func CheckRoom

func CheckRoom(rows int) error

CheckRoom refuses a new session in a workspace that already holds rows rows (InstanceLimit).

func CheckWritable

func CheckWritable(ws WorkspaceView) error

CheckWritable refuses a new session in ws while its storage refuses writes (WorkspaceView.WritesRefused): the session could never be saved.

func ChooseLaunchAccount

func ChooseLaunchAccount(c Core, opts launch.Options, program string) (launch.Options, string)

ChooseLaunchAccount is opts with the account a launch of program runs on, as the Session Launch Options modal pre-fills it, and the notice to show when it moved the launch off a removed account ("" otherwise). The caller reloads the accounts first (Core.ReloadAccounts).

A Claude launch with no account chosen, or with one no longer registered, takes the registry's default, so R on a session whose account was removed can't relaunch as it again; the notice names the switch (RemovedAccountNotice). A registry that failed to load keeps a named account: it lists no accounts, and rewriting the account would move the session to a subscription the user never saw chosen; kept, its launch fails closed (session.RegistryLoadError). Any other program, or a model with no account registry, records no account.

func FetchedIssueForTest

func FetchedIssueForTest(req ReqID, issue github.Issue, err error) any

FetchedIssueForTest is the result FetchIssue's job delivers for request req: issue, or err. A test delivers it in place of running the job, whose gh call it can't make.

func FromWire

func FromWire(w *WireError) error

FromWire decodes a wire error: nil (a nil interface, never a typed nil pointer) for nil.

func GitHubAliasesForTest

func GitHubAliasesForTest(result any, aliases map[string]string) any

GitHubAliasesForTest is a GitHubResultForTest result whose poll found each key of aliases inside the repository named by its value.

func GitHubResultForTest

func GitHubResultForTest(available bool, reason string, snapshots map[string]github.Snapshot, errs map[string]error) any

GitHubResultForTest is a finished GitHub poll's result, for Deliver: gh checked and found available or not (reason says why not), and each repo's snapshot or error.

func Persistable

func Persistable(instances []*session.Instance) []*session.Instance

Persistable filters out instances whose state should not reach disk: a creation flow's instance that has never started (Ready and not Started), Deleting (kill in progress, about to be removed via DeleteInstance), and Recoverable (an orphan surfaced inline; it is re-derived from disk each load and adopted only on explicit recovery, so persisting it would resurrect a never-confirmed entry). Every other instance is persisted — Loading, Running, Prompting, Paused and a started Ready one — so that a crash or quit during the kill window cannot orphan a live worktree from its JSON record.

Ready is overloaded: a creation flow's instance is Ready before it starts, and the status ladder and Claude's roster report an idle agent or workspace terminal as Ready too. Skipping every Ready instance dropped idle sessions' records on each save, so the next load offered their worktrees as Recoverable orphans and killed and recreated an idle workspace terminal.

func RemovedAccountNotice

func RemovedAccountNotice(removed, now string) string

RemovedAccountNotice says a launch whose account was removed runs on another one, which the user sees before confirming.

func RosterResultForTest

func RosterResultForTest(entries map[string]session.RosterEntry, err error, at time.Time) any

RosterResultForTest is a finished roster query's result, for Deliver: entries is the default account's roster, err its failure, at when the query started.

func TrackedForTest

func TrackedForTest(req ReqID, id InstanceID, result any) any

TrackedForTest is result as the job of request req, for the instance id, delivers it, so its Reply follows: a test delivers it in place of running the job, whose real work (adopting an orphan, say) it can't do.

func UntrackedForTest

func UntrackedForTest(result any) any

UntrackedForTest is a job's result with a request's tracking removed: a request's job (Kill, Merge, SendPrompt, …) answers with its operation's result wrapped for its Reply, and a job serving a request (a Create's start) with its result wrapped as caused; any other result comes back as it is.

func UsageResultForTest

func UsageResultForTest(results map[string]account.Usage, errs map[string]error) any

UsageResultForTest is a finished round of usage probes, for Deliver.

Types

type AccountNames

type AccountNames struct {
	Present bool
	Default string
	Names   []string
}

AccountNames are the registered accounts, default first. Present is false until the account registry is set up (InitAccounts).

type AccountsChanged

type AccountsChanged struct {
	View AccountsView
}

AccountsChanged carries the account state whenever the registry, an account's auth, sync report or usage, or the Claude program changed (and on the first Sync): the TUI refreshes every view showing accounts (refreshAccountViews) and whether account UI shows at all (ui.SetShowAccounts), and a replica answers the account queries from it.

type AccountsView

type AccountsView struct {
	// Names is AccountNames(): Present is false without a registry.
	Names AccountNames
	// Loaded: the registry exists and loaded without error.
	Loaded bool
	// Extra: an account besides default is registered.
	Extra bool
	// ClaudeProgram is the Claude program the accounts run with ("" when
	// neither the agent program nor an active session is Claude).
	ClaudeProgram string
	// CredentialOverride names the credential in the model's environment
	// that overrides every account, "" when none does
	// (Core.CredentialOverride).
	CredentialOverride string
	// RunningAsAccount warns that the model runs as an extra account, ""
	// when it does not (Core.RunningAsAccount).
	RunningAsAccount string
	// Accounts are the registered accounts, by name.
	Accounts map[string]account.Account
	// DefaultAuth is the default account's remote-control auth, and Auth
	// each extra account's that a refresh has read.
	DefaultAuth session.RemoteControlAuth
	Auth        map[string]session.RemoteControlAuth
	// Sync is each extra account's last link report.
	Sync map[string]account.SyncReport
	// Usage is each account's latest usage sample, and UsageErr its last
	// probe's failure, if any.
	Usage    map[string]account.Usage
	UsageErr map[string]string
}

AccountsView is the account state (published as AccountsChanged): the registry's accounts and default, each account's remote-control auth, link report, usage and launch env, and the Claude program they run.

func (AccountsView) Account

func (v AccountsView) Account(name string) (account.Account, bool)

Account is the registered account called name (Core.Account).

func (AccountsView) AccountEnv

func (v AccountsView) AccountEnv(name string) ([]string, error)

AccountEnv is the environment that runs Claude as name: nil for the default account, CLAUDE_CONFIG_DIR for a registered one, an error otherwise (Core.AccountEnv; account.Registry.Env).

func (AccountsView) AccountLoggedOut

func (v AccountsView) AccountLoggedOut(acct string) bool

AccountLoggedOut reports that acct's last auth read found it logged out (Core.AccountLoggedOut).

func (AccountsView) AccountNames

func (v AccountsView) AccountNames() AccountNames

AccountNames is the registry's names, default first (Core.AccountNames).

func (AccountsView) AccountSync

func (v AccountsView) AccountSync(name string) (account.SyncReport, bool)

AccountSync is name's last link report (Core.AccountSync).

func (AccountsView) AccountUsage

func (v AccountsView) AccountUsage(name string) (account.Usage, error)

AccountUsage is name's latest usage sample and its last probe's failure (Core.AccountUsage).

func (AccountsView) AccountsLoaded

func (v AccountsView) AccountsLoaded() bool

AccountsLoaded reports that the registry exists and loaded (Core.AccountsLoaded).

func (AccountsView) Clone

func (v AccountsView) Clone() AccountsView

Clone deep-copies v's maps and the reports and samples in them.

func (AccountsView) HasExtraAccounts

func (v AccountsView) HasExtraAccounts() bool

HasExtraAccounts reports that an account besides default is registered (Core.HasExtraAccounts).

func (AccountsView) RCAuthFor

func (v AccountsView) RCAuthFor(acct string) session.RemoteControlAuth

RCAuthFor is acct's remote-control auth: the default account's for "" or default, an extra account's as its last refresh read it, else Unknown (Core.RCAuthFor).

type Alive

type Alive struct {
	IDs    []InstanceID
	Source string
}

Alive lists the IDs of instances whose tmux session a probe found alive. The TUI re-attaches the client of any whose client is not attached (a reattach failed after a full-screen attach, or the client's pump hit EOF on a session since relaunched under its name), unless a full-screen attach owns it. Source names the probe for the TUI's log ("tick", "dead_event").

type ClientsStale

type ClientsStale struct{}

ClientsStale reports that instances stopped being active (killed, paused, reverted): the TUI releases the pane clients no active instance needs (prunePanes).

type Core

type Core interface {
	// The loop: the TUI drains the model when the loop wakes it and after
	// every message.
	Sync() []Event // rpc:client

	// Workspaces: every one the model serves, by ID, and the requests that
	// open one, save them all, register, unregister, rename or reset one
	// and write the registry. Which of them a client shows (its tabs, or
	// the workspace it shows while none is open) is the client's own
	// state.
	Workspaces() []WorkspaceView                    // rpc:local
	Workspace(id WorkspaceID) (WorkspaceView, bool) // rpc:local
	IsLoaded(id WorkspaceID) bool                   // rpc:local
	Open(id WorkspaceID) (WorkspaceView, error)
	SaveForQuit() error
	Registry() RegistryView // rpc:local
	ReloadRegistry() error
	Register(name, dir string) (WorkspaceView, error)
	Unregister(name string) error
	RenameWorkspace(from, to string) error
	Reset(id WorkspaceID, req ReqID) error
	PersistOpenList(names []string)
	SetLastUsed(name string) error

	// A workspace's settings, UI prefs and help screens.
	SaveSettings(id WorkspaceID, settings config.Settings) error
	SetUIPrefs(id WorkspaceID, prefs config.UIPrefs) error
	SetHelpScreensSeen(id WorkspaceID, seen uint32) error

	// Instances: their views, and every lifecycle action as a request by
	// ID, answered by a Reply when it carries a ReqID.
	Views(id WorkspaceID) []InstanceView     // rpc:local
	View(id InstanceID) (InstanceView, bool) // rpc:local
	Create(id WorkspaceID, spec NewInstance, req ReqID)
	Kill(id InstanceID, req ReqID)
	Pause(id InstanceID, req ReqID)
	Resume(id InstanceID, req ReqID)
	ResumeWith(id InstanceID, opts launch.Options, base string, req ReqID)
	Recover(id InstanceID, req ReqID)
	Merge(target, source InstanceID, req ReqID)
	Push(id InstanceID, req ReqID)
	SendPrompt(id InstanceID, text string, req ReqID)
	FetchIssue(repo string, number int, req ReqID)

	// Claude status and the tick: what the TUI's pane events tell the
	// model, and the selected row the model's health tick favours.
	SetSelected(id InstanceID)     // rpc:cast
	MarkOutput(sessionName string) // rpc:cast
	PaneOutput(id InstanceID)      // rpc:cast
	PaneQuiet(id InstanceID)       // rpc:cast
	VerifyDead(id InstanceID)      // rpc:cast

	// The default account's remote-control auth, which sessions launch
	// with.
	RCAuth() session.RemoteControlAuth // rpc:local

	// GitHub: the poll's results, a poll sooner, and a repository the
	// poll covers from now on.
	GitHubSnapshot(repo string) (github.Snapshot, bool) // rpc:local
	GitHubErr(repo string) error                        // rpc:local
	GitHubUnavailable() bool                            // rpc:local
	GitHubUnavailableReason() string                    // rpc:local
	ExpediteGitHub()                                    // rpc:cast
	WatchGitHub(repo string)                            // rpc:cast

	// Accounts: the registry, each account's auth, sync, usage and env,
	// and the account requests.
	AccountNames() AccountNames                         // rpc:local
	AccountsLoaded() bool                               // rpc:local
	HasExtraAccounts() bool                             // rpc:local
	Account(name string) (account.Account, bool)        // rpc:local
	RCAuthFor(acct string) session.RemoteControlAuth    // rpc:local
	AccountLoggedOut(acct string) bool                  // rpc:local
	AccountSync(name string) (account.SyncReport, bool) // rpc:local
	AccountUsage(name string) (account.Usage, error)    // rpc:local
	AccountEnv(name string) ([]string, error)           // rpc:local
	ClaudeProgram() string                              // rpc:local
	CredentialOverride() string                         // rpc:local
	RunningAsAccount() string                           // rpc:local
	ReloadAccounts()
	RequestAccountsRefresh(withDefault bool) // rpc:cast
	RequestUsageProbe()                      // rpc:cast
	AddAccount(name string) (string, error)
	RemoveAccount(name string, force bool) error
	SetDefaultAccount(name string) error
}

Core is the session model as its clients use it: every method the TUI calls. It is value-typed: every parameter and result, and every Event, is plain data a client could be sent from another process, never the model's own objects (TestCoreIsValueTyped). Instances are named by InstanceID and seen as InstanceView values, workspaces by WorkspaceID and WorkspaceView; the registry and accounts cross as copies, and every change is a request. *Loop, the model on its own goroutine, implements it in process: every call is a round trip over that goroutine, the model runs its own jobs and tick, and Loop.Wakes says when to Sync. The core/rpc client implements it over a connection (daemon stage 2). The model is booted before any client connects (Model.Boot) and starts its background work when its loop does (Loop.Begin): neither is a client's.

The rpc package is generated from this file. A method's line comment says how a client serves it:

  • rpc:local answers from the client's replica of the published state (Snapshot, then the state events);
  • rpc:cast is sent one way, with no reply, and publishes nothing, so a cast must change no published state: it marks, names or starts what publishes on its own when it lands;
  • rpc:client never leaves the client (Sync returns the events it received);
  • every other method is a request, whose reply follows the events it produced.

Parameter names are the wire's field names.

type DeadVerified

type DeadVerified struct {
	Instance *session.Instance
	TmuxLive tmux.Liveness
}

DeadVerified is the probe a pane's Dead event asks for (VerifyDead): a dead attach PTY does not always mean a dead session.

type Event

type Event interface {
	// contains filtered or unexported methods
}

Event is something the TUI must apply to its view after a model call. The TUI applies them in order (app.applyCoreEvent).

func EventTypes

func EventTypes() []Event

EventTypes returns a zero value of every concrete Event type: what a codec decodes events into, by type name. TestAllEventsListsEveryEvent keeps it complete.

type GitHubChanged

type GitHubChanged struct {
	View GitHubView
}

GitHubChanged carries the GitHub poll's state whenever a poll lands (and on the first Sync): the TUI refreshes an open issue picker, and a replica answers the GitHub queries from it.

type GitHubView

type GitHubView struct {
	Snapshots map[string]github.Snapshot
	Errs      map[string]string
	// Aliases maps each polled path (canonical) that lies inside another
	// repository's top level, a subdirectory of it, to that top level: a
	// lookup by any spelling finds its repository's state.
	Aliases map[string]string
	// Unavailable: gh was checked and found unusable, for Reason.
	Unavailable bool
	Reason      string
}

GitHubView is the GitHub poll's state (published as GitHubChanged): each open repo's snapshot or its last poll's failure, keyed by its canonical top level, and whether gh is usable.

func (GitHubView) Clone

func (v GitHubView) Clone() GitHubView

Clone deep-copies v's maps and snapshots.

func (GitHubView) GitHubErr

func (v GitHubView) GitHubErr(repo string) error

GitHubErr is repo's last poll failure (Core.GitHubErr), by any spelling of repo (ghRepoKey).

func (GitHubView) GitHubSnapshot

func (v GitHubView) GitHubSnapshot(repo string) (github.Snapshot, bool)

GitHubSnapshot is repo's latest snapshot (Core.GitHubSnapshot), by any spelling of repo (ghRepoKey).

func (GitHubView) GitHubUnavailable

func (v GitHubView) GitHubUnavailable() bool

GitHubUnavailable reports that gh was found unusable (Core.GitHubUnavailable).

func (GitHubView) GitHubUnavailableReason

func (v GitHubView) GitHubUnavailableReason() string

GitHubUnavailableReason is why gh was found unusable (Core.GitHubUnavailableReason).

type HealthChecked

type HealthChecked struct{}

HealthChecked reports that a health tick's probe landed and was applied. The loop arms the next tick then, so probes never overlap; the TUI refreshes the workbench's diff tab.

type HealthResult

type HealthResult struct {
	Results []ProbeResult
}

HealthResult is a health tick probe's result (Tick).

type InstanceID

type InstanceID uint64

InstanceID names one record: a hash of its workspace's canonical config dir, its title and its creation time (idOf), so every daemon over one disk gives it the same ID and a client that rejoins another daemon keeps naming the same sessions. A request naming an ID can't reach another instance: a same-titled one in another workspace differs by config dir, and one created under the title of an instance killed meanwhile by creation time (a collision between two live records probes to the next free value). 0 is never assigned; the TUI uses it for a draft row.

type InstanceView

type InstanceView struct {
	ID    InstanceID
	Title string
	// RepoPath is the repository the session works in (Instance.Path).
	RepoPath     string
	WorktreePath string
	// WorktreeRepoPath is the repository root its worktree belongs to, as
	// git resolved it when the worktree was made (GitWorktree.GetRepoPath):
	// RepoPath through symlinks, or the root above a subdirectory. "" until
	// the instance has started, and for a workspace terminal. Lua's
	// worktree handle is built on it.
	WorktreeRepoPath string
	Branch           string
	// TmuxSession is the agent's tmux session name ("" before it has one);
	// pane clients attach by it. SessionProgram is the program that session
	// was launched with, which picks the client's adapter (its
	// pending-prompt pattern); Program can already name a new one after R.
	TmuxSession    string
	SessionProgram string
	Program        string
	Status         session.Status
	// StatusSince is when Status was entered (zero: not this process).
	StatusSince time.Time
	// StatusReported is set when Claude's hooks or roster have an opinion
	// on the status (Instance.ClaudeStatus). Without one the TUI may show its
	// own pane-scraped status instead (its ladder overlay).
	StatusReported bool
	WaitReason     string
	LastMessage    string
	HasLastMessage bool
	Subagents      []subagent.View
	// Diff is the latest diff stats, valid when HasDiff.
	Diff                git.DiffStats
	HasDiff             bool
	GitHub              github.State
	Ahead, Behind       int
	ParityKnown         bool
	Issue               int
	Account             string
	HeadroomProxy       bool
	CacheTTL1h          bool
	IsWorkspaceTerminal bool
	Started             bool
	// Bell is the TUI's own overlay (a bell rang in the pane since it was
	// last focused). The model never sets it.
	Bell bool
}

InstanceView is an instance as a client sees it: a value copied out of the model (viewOf) carrying everything the TUI renders or gates a key on, and nothing that acts. Clients change an instance only through requests that name its ID. The model publishes each workspace's views when they change (Sync, ViewsChanged).

func CloneViews

func CloneViews(views []InstanceView) []InstanceView

CloneViews deep-copies instance views (cloneViews), for a client that hands out its replica's views: the copies share no memory with it.

func ViewForTest

func ViewForTest(inst *session.Instance, id InstanceID) InstanceView

ViewForTest is the view the model would publish for inst, with ID id: for ui tests that build an instance and render it.

func (InstanceView) Active

func (v InstanceView) Active() bool

Active reports whether the instance is running for the purposes of the background jobs and the TUI's pane clients: started, and not Paused, Deleting, Recoverable or Loading. It is activeInstance's and statusEligible's rule, for a view.

func (InstanceView) Paused

func (v InstanceView) Paused() bool

Paused reports whether the view's status is Paused.

func (InstanceView) StatusAge

func (v InstanceView) StatusAge() time.Duration

StatusAge is how long the instance has been in its status, 0 when no transition was observed this process (as Instance.StatusAge).

type InstancesChanged

type InstancesChanged struct{ Relayout bool }

InstancesChanged reports that instances were added, removed or replaced, or that a lifecycle operation moved their status. The TUI repoints its panes and menu at the selection (instanceChanged); with Relayout it also asks for the window size again (tea.RequestWindowSize), as the old completion did.

type Job

type Job func() any

Job is work the model queues for its loop to run off the model's goroutine. It reads no model state and returns one message (nil for none), which the loop (Loop) delivers back to Deliver.

type KillResult

type KillResult struct {
	Instance *session.Instance
	Title    string
	Notice   error
}

KillResult is a finished kill (Kill): tmux, worktree and branch are gone, or best-effort gone with the failure logged. Notice is what the kill could not finish but the user must see (a stash entry it could not drop).

type Loop

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

Loop runs a Model on a goroutine of its own (daemon stage 1E). It serves every Core method as a round trip over that goroutine, starts the jobs the model queues on goroutines of their own and delivers their results on the loop, fires the model's health tick and hook timer from timers of its own, and signals Wakes when something it did unprompted (a result, a tick) may have produced events for its client to drain (Sync). It implements Core; nothing else touches its model.

Nothing runs on the loop's goroutine except inside a step, and nothing on it waits on its client or calls the loop: a call made from inside a call deadlocks.

func Start

func Start(m *Model) *Loop

Start runs m on a goroutine of its own and returns the loop serving it. From here on only the loop touches m, which is booted already (Model.Boot). The health tick and the hook timer start with Begin; Stop ends the loop.

func StartForTest

func StartForTest(m *Model) *Loop

StartForTest runs m on a loop that keeps every job for the test to run (JobsForTest, then DeliverForTest) and never ticks on its own (TickForTest). Between calls its goroutine is idle, so the test may also reach m directly (ModelForTest): the loop's channel operations order those accesses for the race detector.

func (*Loop) Account

func (l *Loop) Account(name string) (account.Account, bool)

func (*Loop) AccountEnv

func (l *Loop) AccountEnv(name string) ([]string, error)

func (*Loop) AccountLoggedOut

func (l *Loop) AccountLoggedOut(acct string) bool

func (*Loop) AccountNames

func (l *Loop) AccountNames() AccountNames

func (*Loop) AccountSync

func (l *Loop) AccountSync(name string) (account.SyncReport, bool)

func (*Loop) AccountUsage

func (l *Loop) AccountUsage(name string) (account.Usage, error)

func (*Loop) AccountsLoaded

func (l *Loop) AccountsLoaded() bool

func (*Loop) AddAccount

func (l *Loop) AddAccount(name string) (string, error)

func (*Loop) Begin

func (l *Loop) Begin()

Begin starts the model's first background jobs (Model.Begin) and, the first time, the health tick and the hook timer. Whatever serves the loop calls it once, when it starts serving (the daemon, rpc.InProcess); it is not in Core.

func (*Loop) ClaudeProgram

func (l *Loop) ClaudeProgram() string

ClaudeProgram runs Model.ClaudeProgram on the loop.

func (*Loop) Create

func (l *Loop) Create(id WorkspaceID, spec NewInstance, req ReqID)

func (*Loop) CredentialOverride

func (l *Loop) CredentialOverride() string

CredentialOverride runs Model.CredentialOverride on the loop.

func (*Loop) DeliverForTest

func (l *Loop) DeliverForTest(result any)

DeliverForTest delivers a job's result on the loop, as the goroutine that ran the job would (the health probe's result arming the next tick), and returns once it is applied. Its client is not woken.

func (*Loop) ExpediteGitHub

func (l *Loop) ExpediteGitHub()

func (*Loop) FetchIssue

func (l *Loop) FetchIssue(repo string, n int, req ReqID)

func (*Loop) GitHubErr

func (l *Loop) GitHubErr(repo string) error

func (*Loop) GitHubSnapshot

func (l *Loop) GitHubSnapshot(repo string) (github.Snapshot, bool)

func (*Loop) GitHubUnavailable

func (l *Loop) GitHubUnavailable() bool

func (*Loop) GitHubUnavailableReason

func (l *Loop) GitHubUnavailableReason() string

func (*Loop) HasExtraAccounts

func (l *Loop) HasExtraAccounts() bool

func (*Loop) HookTickForTest

func (l *Loop) HookTickForTest()

HookTickForTest runs the model's hook timer tick on the loop, as its timer would (a StartForTest loop never fires it on its own).

func (*Loop) IsLoaded

func (l *Loop) IsLoaded(id WorkspaceID) bool

func (*Loop) JobsForTest

func (l *Loop) JobsForTest() []Job

JobsForTest starts what the model has queued (a seam called on it directly may have queued jobs no step has taken yet), then takes the jobs a StartForTest loop kept, in the order queued.

func (*Loop) Kill

func (l *Loop) Kill(id InstanceID, req ReqID)

func (*Loop) MarkOutput

func (l *Loop) MarkOutput(sessionName string)

func (*Loop) Merge

func (l *Loop) Merge(target, source InstanceID, req ReqID)

func (*Loop) ModelForTest

func (l *Loop) ModelForTest() *Model

ModelForTest returns the loop's model, for its seams. Only a loop that is idle between calls (StartForTest, or a production loop with nothing in flight) may be reached this way.

func (*Loop) Open

func (l *Loop) Open(id WorkspaceID) (WorkspaceView, error)

func (*Loop) OpenedForTest

func (l *Loop) OpenedForTest(id WorkspaceID) bool

OpenedForTest reports, on the loop, whether a client has opened the workspace id since the model started (Core.Open: its first open starts its terminal and its GitHub polling).

func (*Loop) PaneOutput

func (l *Loop) PaneOutput(id InstanceID)

func (*Loop) PaneQuiet

func (l *Loop) PaneQuiet(id InstanceID)

func (*Loop) Pause

func (l *Loop) Pause(id InstanceID, req ReqID)

func (*Loop) PersistOpenList

func (l *Loop) PersistOpenList(names []string)

func (*Loop) Push

func (l *Loop) Push(id InstanceID, req ReqID)

func (*Loop) Quiesce

func (l *Loop) Quiesce(timeout time.Duration) bool

Quiesce readies the loop to stop: no tick or hook tick fires from now on, and it waits until every foreground job has landed (the lifecycle operations a request started, and the jobs their results start), or timeout passes. Background work (polls, probes, scans) is not waited for: its result is dropped at Stop. It reports whether everything landed. A server stopping calls it after it has stopped taking requests, then saves (SaveForQuit), then Stops, so a pause or a kill is never cut off mid-step.

func (*Loop) RCAuth

func (l *Loop) RCAuth() session.RemoteControlAuth

func (*Loop) RCAuthFor

func (l *Loop) RCAuthFor(acct string) session.RemoteControlAuth

func (*Loop) Recover

func (l *Loop) Recover(id InstanceID, req ReqID)

func (*Loop) Register

func (l *Loop) Register(name, dir string) (WorkspaceView, error)

func (*Loop) Registry

func (l *Loop) Registry() RegistryView

func (*Loop) ReloadAccounts

func (l *Loop) ReloadAccounts()

ReloadAccounts runs Model.ReloadAccounts on the loop.

func (*Loop) ReloadRegistry

func (l *Loop) ReloadRegistry() error

func (*Loop) RemoveAccount

func (l *Loop) RemoveAccount(name string, force bool) error

RemoveAccount runs Model.RemoveAccount on the loop.

func (*Loop) RenameWorkspace

func (l *Loop) RenameWorkspace(from, to string) error

RenameWorkspace runs Model.RenameWorkspace on the loop.

func (*Loop) RequestAccountsRefresh

func (l *Loop) RequestAccountsRefresh(withDefault bool)

func (*Loop) RequestUsageProbe

func (l *Loop) RequestUsageProbe()

func (*Loop) Reset

func (l *Loop) Reset(id WorkspaceID, req ReqID) error

Reset runs Model.Reset on the loop.

func (*Loop) Resume

func (l *Loop) Resume(id InstanceID, req ReqID)

func (*Loop) ResumeWith

func (l *Loop) ResumeWith(id InstanceID, opts launch.Options, base string, req ReqID)

func (*Loop) RunningAsAccount

func (l *Loop) RunningAsAccount() string

RunningAsAccount runs Model.RunningAsAccount on the loop.

func (*Loop) SaveForQuit

func (l *Loop) SaveForQuit() error

func (*Loop) SaveSettings

func (l *Loop) SaveSettings(id WorkspaceID, s config.Settings) error

func (*Loop) SelectedForTest

func (l *Loop) SelectedForTest() []InstanceID

SelectedForTest is the model's selection (Model.SelectedForTest), read on the loop, so a test may read it while a server is calling the loop.

func (*Loop) SendPrompt

func (l *Loop) SendPrompt(id InstanceID, text string, req ReqID)

func (*Loop) SetDefaultAccount

func (l *Loop) SetDefaultAccount(name string) error

func (*Loop) SetHelpScreensSeen

func (l *Loop) SetHelpScreensSeen(id WorkspaceID, seen uint32) error

func (*Loop) SetLastUsed

func (l *Loop) SetLastUsed(name string) error

func (*Loop) SetRCAuthForTest

func (l *Loop) SetRCAuthForTest(a session.RemoteControlAuth)

SetRCAuthForTest records the default account's remote-control auth on the loop (Model.SetRCAuth), as Boot's detection does: a change straight to the model, which only the next publish sends to its clients.

func (*Loop) SetSelected

func (l *Loop) SetSelected(id InstanceID)

func (*Loop) SetSelection

func (l *Loop) SetSelection(ids []InstanceID)

SetSelection names every client's selected row at once (Model.SetSelection): a server serving several clients keeps each one's SetSelected and sets their union. It serves the server and is not in Core.

func (*Loop) SetUIPrefs

func (l *Loop) SetUIPrefs(id WorkspaceID, p config.UIPrefs) error

func (*Loop) SpawnForTest

func (l *Loop) SpawnForTest(job Job, background bool)

SpawnForTest queues job on the loop as the model would, a foreground job (spawn) or a background one (spawnBackground), and starts it: a test of what waits for jobs in flight (Quiesce, a daemon stopping).

func (*Loop) Stop

func (l *Loop) Stop()

Stop ends the loop. It waits for the step in progress, then drops every later result (as Bubble Tea dropped a Cmd's result after quit) and closes Wakes. A call after Stop runs nothing and returns zero values. Stop is idempotent; never call it from the loop's goroutine.

func (*Loop) Sync

func (l *Loop) Sync() []Event

func (*Loop) SyncAndSnapshot

func (l *Loop) SyncAndSnapshot() (published, snapshot []Event)

SyncAndSnapshot is a Sync and a Snapshot in one call on the loop, with nothing between them: the events published since the last Sync, then the whole state as it stands after them. A server uses it when a client connects: it sends the first to the connections it has and the second to the new one, whose replica then starts from exactly the state the next Sync diffs against. (A job landing between a Sync and a Snapshot made as two calls could change the model and undo the change before the next Sync, which would show in no diff and leave the new replica stale.) It serves servers: it is not part of Core.

func (*Loop) TickForTest

func (l *Loop) TickForTest()

TickForTest runs the model's health tick on the loop, as its timer would.

func (*Loop) Unregister

func (l *Loop) Unregister(name string) error

Unregister runs Model.Unregister on the loop.

func (*Loop) VerifyDead

func (l *Loop) VerifyDead(id InstanceID)

func (*Loop) View

func (l *Loop) View(id InstanceID) (InstanceView, bool)

func (*Loop) Views

func (l *Loop) Views(id WorkspaceID) []InstanceView

func (*Loop) Wakes

func (l *Loop) Wakes() <-chan struct{}

Wakes says the loop did something unprompted (a job's result landed, the tick fired, a job panicked), so its client should drain (Sync). Wakes coalesce: one waits, however many happened since the last receive. Stop closes it.

func (*Loop) WatchGitHub

func (l *Loop) WatchGitHub(repo string)

WatchGitHub runs Model.WatchGitHub on the loop.

func (*Loop) Workspace

func (l *Loop) Workspace(id WorkspaceID) (WorkspaceView, bool)

func (*Loop) Workspaces

func (l *Loop) Workspaces() []WorkspaceView

type LoopPanic

type LoopPanic struct {
	// Value is what was panicked with.
	Value any
	// Stack is the panicking goroutine's stack.
	Stack string
}

LoopPanic is a panic on the model's goroutine (in a call, a delivery or the tick) or in one of its jobs. The loop re-raises it on the goroutine of the call it happened in, or of the next call after it, so the caller's own recovery sees it: the TUI's Bubble Tea restores the terminal, which a panic on a goroutine of the loop's own would leave in raw mode. The model's state is unknown after one, so every later call re-raises it too, and nothing runs on the model again.

func (*LoopPanic) Error

func (p *LoopPanic) Error() string

type MergeResult

type MergeResult struct {
	Err error
}

MergeResult is a merge job's result (Merge).

type Model

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

Model is the session model (see the package doc). Methods must be called on one goroutine: its loop's (Loop), or a core test's.

func New

func New(o Options) *Model

New builds the model, serving no workspace yet: Boot loads them, before the model's loop starts.

func NewForTest

func NewForTest(o Options) *Model

NewForTest builds a model with no workspace and no side effects; a test installs its fixture's workspaces with SetWorkspacesForTest.

func (*Model) Account

func (m *Model) Account(name string) (account.Account, bool)

Account returns the registered account name.

func (*Model) AccountEnv

func (m *Model) AccountEnv(name string) ([]string, error)

AccountEnv is the environment a command runs with as account name.

func (*Model) AccountLoggedOut

func (m *Model) AccountLoggedOut(acct string) bool

AccountLoggedOut reports that `claude auth status` ran for acct and said it is logged out. Not having asked yet is not logged out.

func (*Model) AccountNames

func (m *Model) AccountNames() AccountNames

AccountNames are the registered accounts, default first; Present is false before InitAccounts.

func (*Model) AccountSync

func (m *Model) AccountSync(name string) (account.SyncReport, bool)

AccountSync returns name's last link report.

func (*Model) AccountUsage

func (m *Model) AccountUsage(name string) (account.Usage, error)

AccountUsage returns name's latest usage sample and the last probe's error (a failed probe keeps the last good sample).

func (*Model) AccountsLoaded

func (m *Model) AccountsLoaded() bool

AccountsLoaded reports whether the registry exists and loaded, so its account list can be trusted to be complete.

func (*Model) AccountsRegistryForTest

func (m *Model) AccountsRegistryForTest() *account.Registry

AccountsRegistryForTest is the model's account registry (nil before InitAccounts): app tests check what an account request did to it.

func (*Model) AddAccount

func (m *Model) AddAccount(name string) (string, error)

AddAccount creates account name (linked against the main config dir) and records its first sync report. The TUI then runs its login.

func (*Model) AdoptAccountsForTest

func (m *Model) AdoptAccountsForTest(reg *account.Registry)

AdoptAccountsForTest installs reg as the registry and publishes it, as InitAccounts does with the one it loads.

func (*Model) AgeGitHubWatchesForTest

func (m *Model) AgeGitHubWatchesForTest(d time.Duration)

AgeGitHubWatchesForTest makes every repository a client asked the poll to cover (WatchGitHub) asked d earlier.

func (*Model) ApplyClaudeStatusForTest

func (m *Model) ApplyClaudeStatusForTest(inst *session.Instance)

ApplyClaudeStatusForTest moves inst to the status its hooks or the roster last reported, as the model does when a hook scan or a roster answer lands (applyClaudeStatus).

func (*Model) Begin

func (m *Model) Begin()

Begin starts the model's first background jobs, each when due: an accounts refresh and a usage probe. Its loop runs it when it starts serving (Loop.Begin).

func (*Model) Boot

func (m *Model) Boot() []Event

Boot readies the model to serve, before its loop starts (the model is single-goroutine until then). In order, it loads the account registry (InitAccounts); detects the default account's remote-control auth, when the global config enables remote control or an extra account is registered (the identity it reads also locates the main config dir the accounts link to); and loads every workspace the model serves (boot). The detection runs once, up front, so every launch decision after it is synchronous. Boot returns the events it raised (the account registry's notices): no client is connected yet to be sent them, so the caller shows them to its own. A client never boots the model: Boot is not in Core.

func (*Model) ClaudeProgram

func (m *Model) ClaudeProgram() string

ClaudeProgram is the Claude CLI loom runs account commands with: the configured program when it is Claude, else a live Claude session's, else "" (no probes).

func (*Model) Create

func (m *Model) Create(id WorkspaceID, spec NewInstance, req ReqID)

Create builds an instance in the workspace id (CreateWS), which refuses a workspace that is not loaded.

func (*Model) CredentialOverride

func (m *Model) CredentialOverride() string

CredentialOverride names the credential set in the model's own environment that overrides every account's login (account.ActiveCredentialOverride), "" when none is. The usage probes and auth reads inherit the model's environment and the remote-control block reason reads it. Since the model runs in the daemon (stage 3B), that environment is the one the daemon was spawned with, possibly from another terminal than a client's, so a client warns from this answer, never from its own environment.

An agent's own environment is another matter. These variables, like the default account's CLAUDE_CONFIG_DIR, are neither in tmux's update-environment nor passed with -e (session.InstanceEnv passes only an extra account's), so an agent inherits them from the tmux server's global environment: the environment of whatever started that server, which is the daemon's only when the daemon started it. Under a server something else started (the user's own, or an earlier daemon's, which the next keeps: daemon.TmuxServer), an agent bills by that server's credential, which this answer does not see.

func (*Model) Deliver

func (m *Model) Deliver(msg any)

Deliver hands the model a job's result. Results the model does not know are logged and dropped.

func (*Model) Drain

func (m *Model) Drain() Out

Drain returns everything produced since the last Drain, and forgets it.

func (*Model) ExpediteGitHub

func (m *Model) ExpediteGitHub()

ExpediteGitHub makes the next tick poll GitHub at once (an in-flight poll still lands first): after a push, an issue-born session, a newly opened workspace.

func (*Model) FetchIssue

func (m *Model) FetchIssue(repo string, n int, req ReqID)

FetchIssue reads issue n of repo through gh (github.View) in a job and answers with the Reply's Issue (or Err).

func (*Model) GateForTest

func (m *Model) GateForTest(kind string, now time.Time) (inFlight, pending, due bool)

GateForTest reports the gate of the job kind names (gateKind's String: "roster", "hook_scan", "github", "usage", "accounts_refresh"): whether a dispatch is in flight, a request is pending, and the gate is due at now.

func (*Model) GitHubErr

func (m *Model) GitHubErr(repo string) error

GitHubErr returns the last poll's error for repo, or nil; repo may be any spelling of it (ghRepoKey).

func (*Model) GitHubReposForTest

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

GitHubReposForTest lists the repositories the next GitHub poll covers (openedRepos), in the order it polls them.

func (*Model) GitHubSnapshot

func (m *Model) GitHubSnapshot(repo string) (github.Snapshot, bool)

GitHubSnapshot returns the latest poll's snapshot of repo, if the last poll of it succeeded; repo may be any spelling of it (ghRepoKey).

func (*Model) GitHubUnavailable

func (m *Model) GitHubUnavailable() bool

GitHubUnavailable reports that gh was checked and found unusable (missing, or not logged in).

func (*Model) GitHubUnavailableReason

func (m *Model) GitHubUnavailableReason() string

GitHubUnavailableReason is why gh was found unusable (CheckCLI's error), for the issue picker's refusal.

func (*Model) HasExtraAccounts

func (m *Model) HasExtraAccounts() bool

HasExtraAccounts reports whether an account besides default is registered; all account UI and polling is gated on it.

func (*Model) HookTick

func (m *Model) HookTick()

HookTick is the loop's hook timer (hookInterval): a hook scan when one is due (maybeHookScan: none in flight, hookScanInterval since the last dispatch), and only while an active Claude instance exists, since only a Claude session writes hook events. With none it does nothing: no job, no gate armed. Either way it changes nothing a client sees (noWake): the scan's result wakes the client if it moved anything. The loop's timer calls it; Loop.HookTickForTest runs it in tests.

func (*Model) IDOfForTest

func (m *Model) IDOfForTest(inst *session.Instance) InstanceID

IDOfForTest returns inst's ID (assigning one): for tests that build instances in the model and then find them through the TUI.

func (*Model) InitAccounts

func (m *Model) InitAccounts()

InitAccounts loads the account registry and publishes it. Called once by the boot (Boot), before the startup auth probe.

func (*Model) InstanceForTest

func (m *Model) InstanceForTest(id InstanceID) *session.Instance

InstanceForTest returns the instance id names, nil when no loaded workspace holds it: for tests that act on the instance behind a row.

func (*Model) IsLoaded

func (m *Model) IsLoaded(id WorkspaceID) bool

IsLoaded reports whether the model serves the workspace id.

func (*Model) Kill

func (m *Model) Kill(id InstanceID, req ReqID)

Kill kills the session id: its pre-step moves it to Deleting at once (the spinner shows), and its job checks, kills and deletes the record (killInst), answering with a KillResult or OpFailed. A Recoverable session is discarded. Refused for a workspace terminal and a busy session (precondition), so a second Kill of the same session is refused while the first runs.

func (*Model) Loaded

func (m *Model) Loaded() []*Workspace

Loaded is every workspace the model serves (Boot): every registered one and the global one, dropped only when it leaves the registry (Unregister, applyRegistry), so this is more than a client shows (its tabs, or the workspace it shows while none is open). It returns a fresh slice, so a caller may keep iterating it while calling back into the model.

func (*Model) MainConfigDir

func (m *Model) MainConfigDir() string

MainConfigDir is the default account's config dir, which extra accounts link to (account.MainDir over the identity read at startup).

func (*Model) MarkOutput

func (m *Model) MarkOutput(sessionName string)

MarkOutput records that a session produced output since the last health tick — the tick uses this to gate diff-stat refreshes.

func (*Model) Merge

func (m *Model) Merge(target, source InstanceID, req ReqID)

Merge merges source's branch into target's worktree (mergeInst). Each must pass its precondition, and they must differ, as the merge picker lists neither a busy session nor the target among the sources. The Reply names target.

func (*Model) Open

func (m *Model) Open(id WorkspaceID) (WorkspaceView, error)

Open is a client showing the workspace id, as a tab or as the workspace it shows while none is open, and returns its view. A workspace whose load failed is loaded again first, and its error returned when it still fails: the client then shows nothing of it. The first open of a workspace starts its terminal (open). An unknown id is an error. Which workspaces a client shows is its own state: an open publishes nothing tab-like, so it changes nothing another client shows.

func (*Model) OutputMarkedForTest

func (m *Model) OutputMarkedForTest(sessionName string) bool

OutputMarkedForTest reports whether sessionName's output is recorded for the next health tick's diff refresh (MarkOutput).

func (*Model) PaneOutput

func (m *Model) PaneOutput(id InstanceID)

PaneOutput reports that id's pane produced output (paneOutputInst).

func (*Model) PaneQuiet

func (m *Model) PaneQuiet(id InstanceID)

PaneQuiet reports that id's pane went quiet (paneQuietInst).

func (*Model) Pause

func (m *Model) Pause(id InstanceID, req ReqID)

Pause pauses the session id: it moves to Loading at once (a refused transition is logged and the pause runs anyway, as the TUI's path always did), then the job stashes, kills the session and removes the worktree (pauseInst). pauseInst is called before the transition, as the TUI's path does, so a failed pause reverts to the status the session had, not to Loading. Refused for a workspace terminal and a busy session (precondition).

func (*Model) PersistOpenList

func (m *Model) PersistOpenList(names []string)

PersistOpenList writes names to the registry's open list, so the next launch restores them: a client's tabs in order, then the workspaces it failed to open and keeps open. The open list is the client's; the model only writes it when asked.

func (*Model) Push

func (m *Model) Push(id InstanceID, req ReqID)

Push commits and pushes the session id's worktree (pushInst). Refused for a workspace terminal and a busy session (precondition).

func (*Model) RCAuth

func (m *Model) RCAuth() session.RemoteControlAuth

RCAuth is the default account's remote-control auth.

func (*Model) RCAuthFor

func (m *Model) RCAuthFor(acct string) session.RemoteControlAuth

RCAuthFor returns acct's remote-control auth: the startup probe for the default account, the refreshed one for an extra account, and Unknown — fail closed, no flag and no prompt — until that has landed.

func (*Model) Recover

func (m *Model) Recover(id InstanceID, req ReqID)

Recover adopts the orphan id, which must be Recoverable (precondition): recoverInst moves it to Loading and its job adopts the worktree, answering with a RecoverResult. Its Reply names the adopted instance, which replaces id's row.

func (*Model) RefreshDefaultAuthForTest

func (m *Model) RefreshDefaultAuthForTest() bool

RefreshDefaultAuthForTest reports whether the next accounts refresh rereads the default account's auth too.

func (*Model) Register

func (m *Model) Register(name, dir string) (WorkspaceView, error)

Register adds dir to the registry as workspace name and returns the view of the workspace the model serves for it from now on, like every registered one, for the client to open (Open, which reports a load that failed). The registry has no lock, so this runs on the model's goroutine, never in a job.

func (*Model) Registry

func (m *Model) Registry() RegistryView

Registry is a copy of the workspace registry: the registered workspaces, the open list (resolved, as GetOpenWorkspaces resolves it) and the last used workspace. Zero in bare tests.

func (*Model) ReloadAccounts

func (m *Model) ReloadAccounts()

ReloadAccounts re-reads accounts.json, which another loom or a `loom account` command may have changed, and handles any change (accountsChanged). The health tick calls it when the file changed (maybeReloadAccounts); the user-paced actions that read the registry — Launch Options, Settings, account requests — call it first regardless.

func (*Model) ReloadRegistry

func (m *Model) ReloadRegistry() error

ReloadRegistry rereads the workspace registry from disk, for a caller about to show it (the workspace picker) or open a workspace it lacks: another process may have changed it since (serveRegistry). A workspace registered since is served too; one no longer registered is unloaded (unload; one with a busy session waits for the next reread), and one registered under another name only is renamed in place, keeping its ID.

func (*Model) RemoveAccount

func (m *Model) RemoveAccount(name string, force bool) error

RemoveAccount removes account name. Without force it refuses while a session uses it (accountUsers) or while its dir holds unshared files (the error then names them and the CLI command that can force it); force overrides both, as `loom account remove --force` does, and logs what it overrode.

func (*Model) RenameWorkspace

func (m *Model) RenameWorkspace(from, to string) error

RenameWorkspace renames registered workspace from to to: in the registry, whose open list and last used workspace follow, and in place in the model, whose workspace keeps its ID (its config dir's, wsIDOf), its sessions and its terminal's title. Refused (ErrRefused) for the global workspace, an unknown from, and a to already registered.

func (*Model) RequestAccountsRefresh

func (m *Model) RequestAccountsRefresh(withDefault bool)

RequestAccountsRefresh asks for an accounts refresh (accountsRefreshJob): now when none is in flight, else once more when the running one lands. withDefault also rereads the default account's auth.

func (*Model) RequestUsageProbe

func (m *Model) RequestUsageProbe()

RequestUsageProbe brings the next probe round forward: the user is about to choose an account (a picker opened) or the accounts changed.

func (*Model) Reset

func (m *Model) Reset(id WorkspaceID, req ReqID) error

Reset resets the served workspace id as `loom reset` does (ResetWorkspace). Its sessions leave the workspace at once, and a job deletes their records, kills the tmux sessions started in its roots and removes its worktrees and their branches. Meanwhile the workspace takes no session (Create) and no terminal (ensureTerminal). The job's outcome is the Reply to req, and a failure is shown as a Notice too; once it lands, an opened workspace gets a fresh terminal, as the next start used to give it.

A refusal (ErrRefused) is returned and, as for every request, is the Reply to req at once (refuse): an unknown workspace, a busy session or a reset already running (busy), and a workspace whose load failed. Its storage refuses writes, since loom can't read its records; the direct path clears that (`loom serve stop`, then `loom reset`).

func (*Model) Resume

func (m *Model) Resume(id InstanceID, req ReqID)

Resume resumes the session id, which must be Paused and not a workspace terminal (precondition; a Recoverable one is Recover's): it moves to Loading at once and the job resumes it (resumeIfLoadingInst), answering with a ResumeResult, or an OpFailed reverting to Paused. The transition can't be refused from Paused; if it were, the request would be refused too.

func (*Model) ResumeWith

func (m *Model) ResumeWith(id InstanceID, opts launch.Options, base string, req ReqID)

ResumeWith resumes the session id with new launch options (the R flow): the program recomposed from base (applyLaunch), then as Resume. Its precondition is Resume's, checked before the options are applied, so a refused request changes nothing.

func (*Model) RunningAsAccount

func (m *Model) RunningAsAccount() string

RunningAsAccount is the warning that loom itself runs as an extra account (noteRunningAsAccount), "" when it does not.

func (*Model) SaveForQuit

func (m *Model) SaveForQuit() error

SaveForQuit saves every workspace the model serves, as the daemon's last step when it stops (internal/daemon; a TUI quitting saves no session). A failed save of a workspace a client opened in this run is returned, for the daemon to log, except the storage's write latch (quitSkipsSave), which no retry could clear.

A workspace nobody opened is still saved, since its records change without a client (its agents are crash-restarted at boot and paused by the tick), but a registered repository on an unmounted or read-only path is no failure of the stop: its failure is only logged, and when its config dir is gone (a deleted or unmounted repository) it is skipped, since the save would create the dir.

func (*Model) SaveSettings

func (m *Model) SaveSettings(id WorkspaceID, s config.Settings) error

SaveSettings replaces the workspace's settings with s and writes its config.json: to its context's config dir, or to the default config dir for a bare context. Then it applies what a settings change does at once: the two launch toggles the session package keeps per config dir (SetLoomContextEnabled, SetSubagentTrackingEnabled) and, for the global workspace only, the agent program the model runs the accounts' Claude commands and orphan placeholders with (m.program, ClaudeProgram): in a daemon that program is the global config's (Options.Program), so one workspace's save must not replace it for every other. The program a client's drafts default to is the client's to follow. An unknown id is an error. Moved from app/state_settings.go, which did this to the model's own config.

func (*Model) SelectedForTest

func (m *Model) SelectedForTest() []InstanceID

SelectedForTest returns the instances the probe refreshes the full diff of (SetSelected, SetSelection).

func (*Model) SendPrompt

func (m *Model) SendPrompt(id InstanceID, text string, req ReqID)

SendPrompt types text into the session id's pane and presses Enter (sendPromptInst). A failure is a notice, and the Reply's Err; a success replies with none. Refused for a session not started or Paused (precondition).

func (*Model) SetAccountAuthForTest

func (m *Model) SetAccountAuthForTest(auth map[string]session.RemoteControlAuth)

SetAccountAuthForTest replaces every extra account's remote-control auth.

func (*Model) SetAccountSyncForTest

func (m *Model) SetAccountSyncForTest(name string, rep account.SyncReport)

SetAccountSyncForTest records name's last link report.

func (*Model) SetAccountUsageForTest

func (m *Model) SetAccountUsageForTest(name string, u account.Usage, err error)

SetAccountUsageForTest records name's usage sample and last probe error.

func (*Model) SetAccountsForTest

func (m *Model) SetAccountsForTest(reg *account.Registry)

SetAccountsForTest replaces the registry without publishing it.

func (*Model) SetDefaultAccount

func (m *Model) SetDefaultAccount(name string) error

SetDefaultAccount makes name the account new sessions preselect.

func (*Model) SetExecForTest

func (m *Model) SetExecForTest(e cmd2.Executor)

SetExecForTest replaces the executor of the workspace load paths.

func (*Model) SetGateForTest

func (m *Model) SetGateForTest(kind string, inFlight bool, last time.Time)

SetGateForTest sets the in-flight flag and last dispatch of the gate of the job kind names.

func (*Model) SetHelpScreensSeen

func (m *Model) SetHelpScreensSeen(id WorkspaceID, seen uint32) error

SetHelpScreensSeen replaces and persists the workspace's seen help screens.

func (*Model) SetLastUsed

func (m *Model) SetLastUsed(name string) error

SetLastUsed records name as the workspace the next launch focuses.

func (*Model) SetRCAuth

func (m *Model) SetRCAuth(a session.RemoteControlAuth)

SetRCAuth records the default account's remote-control auth, as Boot's detection does.

func (*Model) SetRegistryForTest

func (m *Model) SetRegistryForTest(r *config.WorkspaceRegistry)

SetRegistryForTest replaces the workspace registry.

func (*Model) SetRunningAsAccountForTest

func (m *Model) SetRunningAsAccountForTest(text string)

SetRunningAsAccountForTest sets the warning that loom runs as an extra account, as InitAccounts would from its environment.

func (*Model) SetSelected

func (m *Model) SetSelected(id InstanceID)

SetSelected names the instance whose full diff the health tick's probe refreshes: the TUI's selected row, 0 for none. The loop's tick reads it (Loop). With several clients a server sets them all (SetSelection).

func (*Model) SetSelection

func (m *Model) SetSelection(ids []InstanceID)

SetSelection names every instance whose full diff the health tick's probe refreshes: each client's selected row. A server serving several clients keeps each one's SetSelected and sets their union here.

func (*Model) SetUIPrefs

func (m *Model) SetUIPrefs(id WorkspaceID, p config.UIPrefs) error

SetUIPrefs replaces and persists the workspace's UI prefs.

func (*Model) SetWorkspacesForTest

func (m *Model) SetWorkspacesForTest(wss ...*Workspace)

SetWorkspacesForTest installs a fixture's workspaces, served and opened, in serve order (a nil one and a repeat are skipped). The model has not booted: a Boot loads the global and registered workspaces beside them.

func (*Model) Snapshot

func (m *Model) Snapshot() []Event

Snapshot is the whole published state as events, in Sync's order: the workspace views, the model, account and GitHub views, and every served workspace's instance views. It leaves what the next Sync diffs against alone: it is what a client needs when it subscribes, before the diffs.

func (*Model) Sync

func (m *Model) Sync() Out

Sync is syncEvents plus the jobs queued since the last call: everything the model produced, for a caller that runs its jobs itself (core's own tests; until stage 1E, the TUI). The loop (Loop.Sync) uses syncEvents.

func (*Model) Tick

func (m *Model) Tick()

Tick runs the health tick's model half (tickInst), refreshing the full diff of every selected instance (SetSelection) that a loaded workspace holds. The loop's timer calls it.

func (*Model) Unregister

func (m *Model) Unregister(name string) error

Unregister removes workspace name from the registry and stops serving it, saving it first. Its sessions keep running, untouched: registering its directory again serves them anew, under the same IDs, which the disk derives (stableID). Refused (ErrRefused) for the global workspace, which no entry names, an unknown name, and a workspace with a busy session or a reset running (busy), whose completion must find it served. An entry that is another name for a directory still registered (a twin), or for the global workspace's, only leaves the registry: the workspace stays served, under a name still registered (applyRegistry).

func (*Model) VerifyDead

func (m *Model) VerifyDead(id InstanceID)

VerifyDead queues the probe a pane's Dead event asks for on id's session (verifyDeadInst); its result is a DeadVerified as before.

func (*Model) View

func (m *Model) View(id InstanceID) (InstanceView, bool)

View returns the view of the instance id, which a served workspace must hold (false otherwise).

func (*Model) Views

func (m *Model) Views(id WorkspaceID) []InstanceView

Views returns the workspace id's instances as views (ViewsWS); nil for an unknown id.

func (*Model) WatchGitHub

func (m *Model) WatchGitHub(repo string)

WatchGitHub adds repo to the repositories the poll covers, for ghWatchTTL from now, and polls at the next tick (ExpediteGitHub) unless the poll has an answer for it already. A client's issue picker asks for its repository on every open: in global mode, a TUI started in a repository no opened workspace or global session names, which the poll would otherwise never cover. A repository watched already (compared canonically) is renewed, and one the poll has answered for (a snapshot or an error) is not polled again at once, so a picker opened again costs no gh calls. A path that is not absolute is not watched. One an opened workspace's poll covers already, under any spelling or from a subdirectory, is polled once (openedRepos, ghPollJob), and the client finds its state by the path it asked with (ghRepoKey). Expired watches are dropped here.

func (*Model) Workspace

func (m *Model) Workspace(id WorkspaceID) (WorkspaceView, bool)

Workspace is the view of the served workspace id; false when the model serves none with it.

func (*Model) WorkspaceForTest

func (m *Model) WorkspaceForTest(id WorkspaceID) *Workspace

WorkspaceForTest resolves a loaded workspace's ID to the model's workspace, nil when none is loaded: app tests reach a fixture's instances through it.

func (*Model) WorkspaceIDForTest

func (m *Model) WorkspaceIDForTest(ws *Workspace) WorkspaceID

WorkspaceIDForTest is ws's ID, assigned on first use.

func (*Model) Workspaces

func (m *Model) Workspaces() []WorkspaceView

Workspaces are the views of every workspace the model serves, in serve order: what a client opens one by (Open) and shows a failed load from (LoadErr).

type ModelChanged

type ModelChanged struct {
	View ModelView
}

ModelChanged carries the model's own state (the default account's remote-control auth and the workspace registry) whenever it changed, and on the first Sync. The TUI does nothing with it; a replica answers those queries from it.

type ModelView

type ModelView struct {
	RCAuth   session.RemoteControlAuth
	Registry RegistryView
}

ModelView is the model's own state: the default account's remote-control auth and the workspace registry (published as ModelChanged).

func (ModelView) Clone

func (v ModelView) Clone() ModelView

Clone deep-copies v's slices; every other field is a value already.

type NewInstance

type NewInstance struct {
	Title   string
	Path    string // the repository it works in
	Program string // the base program; Launch is composed onto it
	Prompt  string // sent once it has started
	Branch  string // the branch picker's choice; "" for a new branch
	Issue   int    // the GitHub issue it was made from, 0 for none
	// Launch is the Session Launch Options choice. Its account and branch
	// prefix are recorded on the instance; the rest is composed onto
	// Program with the account's remote-control auth (applyLaunch). Only
	// with Start.
	Launch launch.Options
	// Start starts it at once (the creation flows). Without it the
	// instance is added unstarted (a script's ctx:new_instance).
	Start bool
}

NewInstance describes an instance to create (Create).

type Notice

type Notice struct {
	Err  error
	Info string
	Req  ReqID
}

Notice is a line for the error bar: Err as an error (shown longer the longer it is, and logged), or else Info as an info line. Req names the request whose job it reports on (a failed job, a stash it forgot), 0 for one the model raised on its own: a server sends a request's notices to the client that made it alone.

func (Notice) MarshalJSON

func (n Notice) MarshalJSON() ([]byte, error)

MarshalJSON encodes n with its error as a WireError.

func (*Notice) UnmarshalJSON

func (n *Notice) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes a Notice MarshalJSON encoded.

type OpFailed

type OpFailed struct {
	Instance *session.Instance
	Title    string
	Op       string
	Previous session.Status
	Err      error
}

OpFailed is a kill, discard, pause or resume that failed: the instance goes back to Previous so the user can retry.

type Options

type Options struct {
	// Registry is the workspace registry; nil in bare tests.
	Registry *config.WorkspaceRegistry
	// Program is the global config's agent program, as the daemon starts
	// the model (loom serve). The model detects the default account's
	// remote-control auth with it (Boot), and runs the accounts' Claude
	// commands (ClaudeProgram) and orphan placeholders with it, until the
	// global workspace's settings save replaces it (SaveSettings); each
	// client keeps the program its own drafts default to.
	Program string
	// CmdExec replaces cmd.MakeExecutor() on the workspace load paths: a
	// test seam. nil in production.
	CmdExec cmd2.Executor
	// GHExec replaces the executor FetchIssue runs gh with: a test seam
	// (a daemon test holds a request's job with it). nil in production.
	GHExec cmd2.Executor
}

Options configure a Model.

type Out

type Out struct {
	Events []Event
	Jobs   []Job
}

Out is what the model produced since the last Drain: events for the TUI and jobs to run, each in the order produced.

func (Out) Empty

func (o Out) Empty() bool

Empty reports whether o holds nothing.

type PauseResult

type PauseResult struct {
	Title string
}

PauseResult is a finished pause (Pause).

type ProbeResult

type ProbeResult struct {
	Instance *session.Instance
	TmuxLive tmux.Liveness
	DiffErr  error
}

ProbeResult is one instance's health probe: its tmux liveness and, for a live one, whether its diff refresh failed. Exported so the TUI's tests can deliver a HealthResult.

type Reactivated

type Reactivated struct {
	ID InstanceID
}

Reactivated reports that a failed operation put the instance ID back to its previous status. A tick may have pruned its client while it was Deleting or Loading, so the TUI ensures one (ensurePane, a no-op unless the instance is active).

type RecoverResult

type RecoverResult struct {
	Placeholder *session.Instance
	Owner       *Workspace
	OldTitle    string
	Recovered   *session.Instance
	Err         error
}

RecoverResult is a recover job's result (Recover). Placeholder is the Recoverable row it adopts, OldTitle its title; Recovered is the adopted instance, or Err why adoption failed.

type Recovered

type Recovered struct {
	Req    ReqID
	ID     InstanceID
	Title  string
	Owner  WorkspaceID
	Paused bool
	// OwnerLabel is as for Started.
	OwnerLabel string
}

Recovered reports an orphan adopted into its placeholder's row. Req, Owner, ID and Title are as for Started. Paused is set when adoption could only mark the record Paused (its session and worktree were gone).

type RecoverySummary

type RecoverySummary struct {
	Cleaned int // stale worktrees auto-removed
	Review  int // Recoverable entries added to the list
	Failed  int // records that failed reconcile (storage unrecovered cache)
	// Undecodable counts records this binary cannot decode (corrupt, or
	// written by a newer loom); storage preserves them verbatim.
	Undecodable int
}

RecoverySummary tallies what a reconcileOrphans pass did, for the non-blocking one-line summary shown to the user.

func (RecoverySummary) Empty

func (s RecoverySummary) Empty() bool

func (RecoverySummary) String

func (s RecoverySummary) String() string

type RegistryView

type RegistryView struct {
	Workspaces []config.Workspace
	Open       []config.Workspace
	LastUsed   string
}

RegistryView is a copy of the workspace registry: every registered workspace, the open tabs to restore (the open list resolved to its registered workspaces, in order, as GetOpenWorkspaces resolves it), and the workspace last focused, which a restore focuses.

type Reply

type Reply struct {
	Req    ReqID
	ID     InstanceID
	Err    error
	Notice error
	Issue  github.Issue
}

Reply answers a request made with a ReqID: at once when the request is refused, when it finishes for a long operation. ID names the instance it concerns (for Create the new one, for Recover the adopted one). Err is the failure. Notice is what a success must still show (a stash it could not drop). Issue is FetchIssue's result. The notices the TUI shows for an operation are emitted as usual; the Reply is for the requester that waits on it.

func (Reply) MarshalJSON

func (r Reply) MarshalJSON() ([]byte, error)

MarshalJSON encodes r with its errors as WireErrors.

func (*Reply) UnmarshalJSON

func (r *Reply) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes a Reply MarshalJSON encoded.

type ReqID

type ReqID uint64

ReqID names a request so its Reply can find the requester. The client chooses it; 0 asks for no Reply.

type ResetReport

type ResetReport struct {
	// Records: the workspace's stored instances were deleted.
	Records bool
	// Sweep is what the sweep of its tmux sessions did, once it ran; Swept
	// that it ran and every kill landed.
	Sweep session.SweepResult
	Swept bool
	// Worktrees: its worktrees and their branches were removed.
	Worktrees bool
}

ResetReport says how far a reset got (ResetWorkspace), step by step.

func ResetWorkspace

func ResetWorkspace(ctx *config.WorkspaceContext, registry *config.WorkspaceRegistry, exec cmd2.Executor) (ResetReport, error)

ResetWorkspace resets the workspace of ctx from its records on disk, as `loom reset` does with no daemon running (the model's Reset runs the same steps over the records it serves). In order, it

  1. deletes the workspace's stored instances, and the records storage preserves beside them (undecodable or unrecovered);
  2. kills the loom tmux sessions started in its repository or worktrees dir, and none of another workspace's (registry tells them apart; nil when it can't be read), with exec;
  3. removes its worktrees and their branches: unpushed commits on them are lost.

A sweep that fails stops it before step 3: some of the workspace's agents may still be running in those worktrees. The report says how far it got.

type ResumeResult

type ResumeResult struct {
	Instance   *session.Instance
	Owner      *Workspace
	Notice     error
	Relaunched bool
}

ResumeResult is a resume that succeeded (resumeIfLoadingInst). Notice, when set, is what it found that the user must see: a stash it forgot or could not drop (session.Notice). Relaunched says it launched the agent anew (session.Instance.Launches moved) rather than reattach to its live session, so the launch is watched for a trust prompt. A failed resume is an OpFailed.

type SessionLaunched

type SessionLaunched struct {
	ID InstanceID
}

SessionLaunched reports that the tmux session of the instance ID was (re)launched or reattached while a loaded workspace holds it, so any pane client from before watched the session it replaced: the TUI gives it a fresh one (replacePane).

type StartResult

type StartResult struct {
	Instance *session.Instance
	Owner    *Workspace
	Err      error
}

StartResult is a start job's result (startInst): the instance, Start's error, and the workspace that owned it at dispatch.

type Started

type Started struct {
	Req   ReqID
	ID    InstanceID
	Title string
	Owner WorkspaceID
	// OwnerLabel names the owner in notices ("global" when unknown).
	OwnerLabel string
}

Started reports a start that succeeded. Owner names the workspace that holds the instance (0 when unknown); the TUI attaches its client, and selects it or says where it started. ID and Title are the instance's. Req is the request that started it (a Create), 0 for none: only the client that asked selects the row and attaches inline, while every client attaches its pane.

type StatusesChanged

type StatusesChanged struct{}

StatusesChanged reports that instance statuses may have moved (a probe, a hook scan, a roster answer): the TUI refreshes its tab statuses and peer sections (updateTabBarStatuses).

type ViewsChanged

type ViewsChanged struct {
	// WS names the workspace: the TUI's slot for it.
	WS    WorkspaceID
	Views []InstanceView
}

ViewsChanged carries a served workspace's instance views, in display order, whenever any of them changed since the last Sync. The TUI replaces its store for that workspace with Views, when it shows the workspace. Sync puts these first in the events it returns, so the appliers of the events that follow see the new views.

type WireError

type WireError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

WireError is an error as it crosses a process boundary: its message, and a code that keeps the identities clients test with errors.Is (ErrNoSession, ErrUnavailable, ErrRefused, session.ErrStorageLoadFailed). Every other error arrives as text only, which is all the TUI does with one.

func ToWire

func ToWire(err error) *WireError

ToWire encodes err for the wire: nil for nil, a WireError unchanged, an error wrapping one (decode params: %w) under that one's code with the whole message, anything else its message under the code of the first sentinel it matches (CodeError for none).

func (*WireError) Error

func (e *WireError) Error() string

func (*WireError) Is

func (e *WireError) Is(target error) bool

Is keeps the sentinel identities a client checks: a not_found error is ErrNoSession (and so ErrRefused, as ErrNoSession is a refusal), an unavailable one ErrUnavailable (a refusal too), a refused one ErrRefused, a storage one session.ErrStorageLoadFailed.

type Workspace

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

Workspace is one loaded workspace: its context, the storage its instances persist to, its config and app state, its instances in display order, and the summary of its last orphan reconcile. The model owns it; the TUI reads it (its slot is a view over it) and changes its instances only through Add, Remove and Replace. Its context changes only by a rename (renameWS, which gives it a renamed copy) and its storage, config and state only by a reread from disk (reloadWS).

func NewWorkspace

func NewWorkspace(p WorkspaceParts) *Workspace

NewWorkspace builds a workspace with no instances.

func (*Workspace) AddForTest

func (w *Workspace) AddForTest(inst *session.Instance)

AddForTest adds inst to w as the model's own edits do (Workspace.add): for tests that build instances and install them in a fixture workspace.

func (*Workspace) Config

func (w *Workspace) Config() *config.Config

Config is the workspace's config.json.

func (*Workspace) Ctx

func (w *Workspace) Ctx() *config.WorkspaceContext

Ctx is the workspace's context; nil only in bare test fixtures.

func (*Workspace) InstancesForTest

func (w *Workspace) InstancesForTest() []*session.Instance

InstancesForTest returns w's instances, in display order (the model's own slice; a test must not modify it).

func (*Workspace) Label

func (w *Workspace) Label() string

Label names the workspace in notices: its name, or "global" (also for a nil workspace).

func (*Workspace) Name

func (w *Workspace) Name() string

Name is the workspace's registered name, "" for the global context (and for a nil workspace).

func (*Workspace) Recovery

func (w *Workspace) Recovery() RecoverySummary

Recovery is the summary of the workspace's last orphan reconcile.

func (*Workspace) RemoveForTest

func (w *Workspace) RemoveForTest(inst *session.Instance) bool

RemoveForTest removes inst from w by identity, as the model's own edits do (Workspace.remove): for tests that stand in for a removal.

func (*Workspace) State

func (w *Workspace) State() config.AppState

State is the workspace's state.json: help screens seen and UI prefs.

func (*Workspace) Storage

func (w *Workspace) Storage() *session.Storage

Storage persists the workspace's instances.

type WorkspaceID

type WorkspaceID uint64

WorkspaceID names a workspace the model serves: a hash of its canonical config dir (wsIDOf), so every daemon over one disk gives it the same ID. A workspace keeps its ID while the model serves it, which is until the model stops (a tab closed and reopened shows the same workspace); a collision between two served workspaces probes to the next free value. 0 means none.

type WorkspaceParts

type WorkspaceParts struct {
	Ctx     *config.WorkspaceContext
	Storage *session.Storage
	Config  *config.Config
	State   config.AppState
}

WorkspaceParts are a workspace's fixed handles. Any may be nil, as in a test's bare fixture.

type WorkspaceView

type WorkspaceView struct {
	ID WorkspaceID
	// Name is the registered name, "" for the global context; Label names
	// it in notices (its name, or "global").
	Name, Label string
	// RepoPath and ConfigDir are the workspace context's ("" in a bare
	// context).
	RepoPath, ConfigDir string
	// Settings is a copy of the workspace's config.json.
	Settings config.Settings
	// UIPrefs and HelpScreensSeen are copies of its state.json.
	UIPrefs         config.UIPrefs
	HelpScreensSeen uint32
	// WritesRefused is set while the workspace's storage refuses writes
	// (its load failed: Storage.WritesRefused). PreservedTitles are the
	// titles of records its storage preserves but could not load.
	WritesRefused   bool
	PreservedTitles []string
	// Recovery is the summary of its last orphan reconcile.
	Recovery RecoverySummary
	// LoadErr is the text of the error its storage failed to load with,
	// "" once it loaded: what a client can show a failed workspace with.
	// Opening it retries the load (Core.Open), which reports the error
	// again if it still fails.
	LoadErr string
}

WorkspaceView is a served workspace as its clients see it: a value the model publishes (WorkspacesChanged) and answers queries with. Every field is a copy.

func CloneWorkspaceViews

func CloneWorkspaceViews(views []WorkspaceView) []WorkspaceView

CloneWorkspaceViews deep-copies workspace views (cloneWorkspaceViews).

type WorkspacesChanged

type WorkspacesChanged struct {
	Views []WorkspaceView
}

WorkspacesChanged carries every served workspace's view, in serve order, whenever any of them (or the served set) changed since the last Sync. Sync puts it first, ahead of ViewsChanged, so the appliers of everything after it see the new workspace views. Which of them a client shows is its own state.

type WorkspacesView

type WorkspacesView struct {
	Views []WorkspaceView
}

WorkspacesView is every served workspace's view, in serve order.

func (WorkspacesView) IsLoaded

func (w WorkspacesView) IsLoaded(id WorkspaceID) bool

IsLoaded reports whether the workspace id is served (Core.IsLoaded).

func (WorkspacesView) Workspace

func (w WorkspacesView) Workspace(id WorkspaceID) (WorkspaceView, bool)

Workspace is the view of the served workspace id (Core.Workspace).

func (WorkspacesView) Workspaces

func (w WorkspacesView) Workspaces() []WorkspaceView

Workspaces are the served workspaces' views, in serve order (Core.Workspaces): never nil.

Directories

Path Synopsis
rpc
Package rpc carries core.Core over a connection (daemon stage 2): newline-delimited JSON frames, a Server serving a core.Loop, and a Client implementing core.Core.
Package rpc carries core.Core over a connection (daemon stage 2): newline-delimited JSON frames, a Server serving a core.Loop, and a Client implementing core.Core.
internal/gen
Package gen generates core/rpc's wire code from core.Core (core/iface.go): every method's parameter and result types, the method table, the server's dispatch, and the client's methods.
Package gen generates core/rpc's wire code from core.Core (core/iface.go): every method's parameter and result types, the method table, the server's dispatch, and the client's methods.
internal/gen/cmd command
Command cmd writes core/rpc/methods_gen.go from core/iface.go.
Command cmd writes core/rpc/methods_gen.go from core/iface.go.

Jump to

Keyboard shortcuts

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