Documentation
¶
Overview ¶
Package session owns the core domain: a running AI coding agent represented by the Instance type.
An Instance moves through a small lifecycle — Ready → Loading → Running → Paused (and optionally Killed) — coordinating with neighbouring packages at each stage: session/git for worktree creation and cleanup, session/tmux for the PTY that drives the agent, and session/agent for program-specific behaviour such as trust-prompt handling and recovery flags.
Persistence lives in storage.go and is versioned via CurrentSchemaVersion; when the on-disk InstanceData schema changes, bump the constant and add an upgrade step in storage_migrate.go. State transitions are validated through Instance.TransitionTo; disallowed edges return an error rather than silently mutating.
Index ¶
- Constants
- Variables
- func BuildRecoveryCommand(program string) string
- func CheckTmuxAlive(sessionTitle string, cmdExec internalexec.Executor) bool
- func CheckWorktreeExists(worktreePath string) bool
- func CleanupOrphanedSessions(claimedTitles map[string]bool, cmdExec internalexec.Executor) error
- func IsAllowedTransition(from, to Status) bool
- func KillTmuxSessionByTitle(title string, cmdExec internalexec.Executor) error
- type DiffStatsData
- type GitWorktreeData
- type Instance
- func (i *Instance) CaptureAndProcessStatus() (updated bool, hasPrompt bool, err error)
- func (i *Instance) CheckAndHandleTrustPrompt() bool
- func (i *Instance) CrashRestart() error
- func (i *Instance) EnsureRunning() error
- func (i *Instance) GetBranch() string
- func (i *Instance) GetContentHash() []byte
- func (i *Instance) GetDiffStats() *git.DiffStats
- func (i *Instance) GetGitWorktree() (*git.GitWorktree, error)
- func (i *Instance) GetStatus() Status
- func (i *Instance) GetWorktreePath() string
- func (i *Instance) HasUpdated() (updated bool, hasPrompt bool)
- func (i *Instance) Kill() (err error)
- func (i *Instance) Pause(saveState func() error) (err error)
- func (i *Instance) Paused() bool
- func (i *Instance) Preview() (string, error)
- func (i *Instance) PreviewFullHistory() (string, error)
- func (i *Instance) RepoName() (string, error)
- func (i *Instance) Resume(saveState func() error) (err error)
- func (i *Instance) SendKeys(keys string) error
- func (i *Instance) SendKeysRaw(b []byte) error
- func (i *Instance) SendPrompt(prompt string) error
- func (i *Instance) SetPreviewSize(width, height int) error
- func (i *Instance) SetSelectedBranch(branch string)
- func (i *Instance) SetTitle(title string) error
- func (i *Instance) SetTmuxSession(session *tmux.TmuxSession)
- func (i *Instance) ShouldRefreshDiff(tmuxUpdated, wantFull bool) bool
- func (i *Instance) Snapshot() InstanceData
- func (i *Instance) Start(firstTimeSetup bool) (err error)
- func (i *Instance) Started() bool
- func (i *Instance) TapEnter()
- func (i *Instance) TmuxAlive() bool
- func (i *Instance) TmuxSession() *tmux.TmuxSession
- func (i *Instance) ToInstanceData() InstanceData
- func (i *Instance) TransitionTo(to Status) error
- func (i *Instance) UpdateDiffStats() error
- func (i *Instance) UpdateDiffStatsShort() error
- type InstanceData
- type InstanceOptions
- type RecoveryAction
- type SessionBackend
- type Status
- type Storage
- func (s *Storage) DeleteAllInstances() error
- func (s *Storage) DeleteInstance(title string) error
- func (s *Storage) LoadAndReconcile(cmdExec internalexec.Executor) ([]*Instance, error)
- func (s *Storage) LoadInstanceData() ([]InstanceData, error)
- func (s *Storage) LoadInstances() ([]*Instance, error)
- func (s *Storage) SaveInstances(instances []*Instance) error
- func (s *Storage) UpdateInstance(instance *Instance) error
Constants ¶
const CurrentSchemaVersion = 1
CurrentSchemaVersion is the schema version written by the current binary. Any on-disk InstanceData with a lower SchemaVersion is routed through storage_migrate.go's Migrate before use.
Variables ¶
var ErrInstanceNotFound = errors.New("instance not found")
ErrInstanceNotFound signals that a storage mutation (delete, update) referenced a title that is no longer persisted. Callers performing idempotent cleanup — e.g. the kill path, where Kill() has already destroyed tmux + worktree before DeleteInstance runs — can match it with errors.Is to distinguish "already gone" from a real write error.
Functions ¶
func BuildRecoveryCommand ¶
BuildRecoveryCommand modifies a program command string for crash recovery. The adapter registry decides whether and how the string is modified (e.g. "claude" → "claude --continue"). Unsupported agents are returned unchanged.
func CheckTmuxAlive ¶
func CheckTmuxAlive(sessionTitle string, cmdExec internalexec.Executor) bool
CheckTmuxAlive checks if a tmux session exists by its sanitized name.
func CheckWorktreeExists ¶
CheckWorktreeExists checks if the worktree directory exists on disk.
func CleanupOrphanedSessions ¶
func CleanupOrphanedSessions(claimedTitles map[string]bool, cmdExec internalexec.Executor) error
CleanupOrphanedSessions kills any tmux sessions with the loom or legacy claude-squad prefix that are not claimed by a loaded instance. Legacy-prefixed sessions are swept too so upgrades from claude-squad don't leave zombie panes behind.
func IsAllowedTransition ¶
IsAllowedTransition reports whether from → to is permitted by the Status state machine. Self-transitions are always allowed.
func KillTmuxSessionByTitle ¶
func KillTmuxSessionByTitle(title string, cmdExec internalexec.Executor) error
KillTmuxSessionByTitle kills the tmux session matching title's sanitized name. Best-effort: returns the command error if any (commonly a benign "session not found"), which most callers can ignore. Used to clear orphan sessions left over from a prior crash before reusing the title.
Types ¶
type DiffStatsData ¶
type DiffStatsData struct {
Added int `json:"added"`
Removed int `json:"removed"`
Content string `json:"content"`
}
DiffStatsData represents the serializable data of a DiffStats
type GitWorktreeData ¶
type GitWorktreeData struct {
RepoPath string `json:"repo_path"`
WorktreePath string `json:"worktree_path"`
SessionName string `json:"session_name"`
BranchName string `json:"branch_name"`
BaseCommitSHA string `json:"base_commit_sha"`
IsExistingBranch bool `json:"is_existing_branch"`
}
GitWorktreeData represents the serializable data of a GitWorktree
type Instance ¶
type Instance struct {
// Title is the title of the instance.
Title string
// Path is the path to the workspace.
Path string
// Branch is the branch of the instance.
Branch string
// Status is the status of the instance.
Status Status
// Program is the program to run in the instance.
Program string
// Height is the height of the instance.
Height int
// Width is the width of the instance.
Width int
// CreatedAt is the time the instance was created.
CreatedAt time.Time
// UpdatedAt is the time the instance was last updated.
UpdatedAt time.Time
// AutoYes is true if the instance should automatically press enter when prompted.
AutoYes bool
// Prompt is the initial prompt to pass to the instance on startup
Prompt string
// ConfigDir is the workspace config directory for worktree resolution.
ConfigDir string
// IsWorkspaceTerminal is true if this instance operates in the root repo without a worktree.
IsWorkspaceTerminal bool
// CrashRecovered is a runtime-only flag set when this instance was restored
// after a crash. Used to trigger agent-aware restart (e.g. --continue).
CrashRecovered bool
// contains filtered or unexported fields
}
Instance is a single agent session managed by Loom. Each Instance owns a git worktree (or, for workspace terminals, targets the root repo) and a tmux session where the agent command runs. Instances move through the Status state machine — Ready → Loading → Running → Paused → Deleting — governed by allowedTransitions; use TransitionTo for every status write.
Field access rules: mu guards Status, diffStats, Branch, tmuxSession, gitWorktree, and the started/starting flags. External callers must go through the exported accessors (GetStatus, GetBranch, GetDiffStats, Snapshot, TmuxSession) or the unexported get*/set* helpers — never read or write those fields directly. Holding mu across I/O is forbidden.
Lifecycle entry points: NewInstance creates a blank instance (call Start(true) to materialize worktree + tmux). FromInstanceData rehydrates persisted state and does not spawn a PTY — callers must invoke EnsureRunning to bring a non-paused instance back online.
func FromInstanceData ¶
func FromInstanceData(data InstanceData, configDir string) (*Instance, error)
FromInstanceData creates a new Instance from serialized data without spawning a tmux PTY attachment. Paused instances are constructed fully (started=true, TmuxSession object present, no PTY — matches their on-disk shape). Non-paused instances are returned with started=false; the caller must invoke EnsureRunning to attach the PTY. configDir is injected for workspace-scoped worktree resolution.
func NewInstance ¶
func NewInstance(opts InstanceOptions) (*Instance, error)
NewInstance constructs a blank Instance in the Ready state. No git worktree or tmux session is allocated until Start(true) runs — this constructor only captures the caller's intent. The workspace path is resolved to an absolute path so worktree setup is not affected by later chdir calls.
func ReconcileAndRestore ¶
func ReconcileAndRestore(data InstanceData, configDir string, cmdExec internalexec.Executor) (*Instance, error)
ReconcileAndRestore loads an instance from serialized data, checks the health of its tmux session and worktree, and takes the appropriate recovery action.
func (*Instance) CaptureAndProcessStatus ¶
CaptureAndProcessStatus captures tmux pane content once and checks for trust prompts and content updates. Avoids duplicate CapturePaneContent calls. Returns a non-nil err when the underlying capture failed — previously the error was swallowed inside tmux.CaptureAndProcess and surfaced only in the log file, so callers saw "no updates" instead of a genuine capture failure.
func (*Instance) CheckAndHandleTrustPrompt ¶
CheckAndHandleTrustPrompt detects and dismisses an agent-specific trust prompt (e.g., Claude's folder-trust dialog) when the agent adapter declares a TrustPromptResponse. Returns true when a prompt was detected and dismissed. No-op for unknown programs.
func (*Instance) CrashRestart ¶
CrashRestart starts a new tmux session for a crash-recovered instance. The worktree already exists (for regular instances) or is unnecessary (for workspace terminals). The program is modified with --continue for supported agents.
func (*Instance) EnsureRunning ¶
EnsureRunning attaches a PTY to the instance's tmux session, restoring any previously-persisted session state. A no-op for paused instances (they deliberately have no PTY) and for already-started instances. Idempotent: the underlying Start guards against double-attaches.
func (*Instance) GetBranch ¶
GetBranch returns the branch name under a read lock. Safe to call concurrently with UpdateDiffStats* for workspace terminals, which refresh Branch on every tick.
func (*Instance) GetContentHash ¶
GetContentHash returns the content hash of the last captured tmux pane.
func (*Instance) GetDiffStats ¶
GetDiffStats returns the current git diff statistics
func (*Instance) GetGitWorktree ¶
func (i *Instance) GetGitWorktree() (*git.GitWorktree, error)
GetGitWorktree returns the git worktree for the instance
func (*Instance) GetWorktreePath ¶
GetWorktreePath returns the worktree path for the instance, or empty string if unavailable. For workspace terminals, returns the root repo path.
func (*Instance) HasUpdated ¶
HasUpdated reports whether the tmux pane content has changed since the last call and whether an auto-yes-eligible prompt is currently visible. Returns (false, false) for non-started instances.
func (*Instance) Pause ¶
Pause stops the tmux session and removes the worktree, preserving the branch. If saveState is non-nil, it is called after committing changes and marking the instance as Paused, providing a checkpoint that reduces the crash inconsistency window.
func (*Instance) Paused ¶
Paused reports whether the instance is currently in the Paused state (worktree removed, branch preserved; can be resumed with Resume).
func (*Instance) Preview ¶
Preview returns the current visible tmux pane content. Returns empty string (not an error) when the instance is not started or paused — the live tail is only meaningful for running sessions.
func (*Instance) PreviewFullHistory ¶
PreviewFullHistory captures the entire tmux pane output including full scrollback history
func (*Instance) RepoName ¶
RepoName returns the human-visible repo/workspace name, delegating to the instance's backend. Errors if called before the instance has been started.
func (*Instance) Resume ¶
Resume recreates the worktree and restarts the tmux session. If saveState is non-nil, it is called after the instance is Running, providing a checkpoint that reduces the crash inconsistency window.
func (*Instance) SendKeysRaw ¶
SendKeysRaw writes raw bytes to the tmux PTY. Used by inline attach mode.
func (*Instance) SendPrompt ¶
SendPrompt sends a prompt to the tmux session
func (*Instance) SetPreviewSize ¶
SetPreviewSize resizes the detached tmux pane so capture output matches the preview viewport. Returns an error if the instance is not running; paused instances have no live pane to resize.
func (*Instance) SetSelectedBranch ¶
SetSelectedBranch sets the branch to use when starting the instance.
func (*Instance) SetTitle ¶
SetTitle sets the title of the instance. Returns an error if the instance has started. We cant change the title once it's been used for a tmux session etc.
func (*Instance) SetTmuxSession ¶
func (i *Instance) SetTmuxSession(session *tmux.TmuxSession)
SetTmuxSession sets the tmux session for testing purposes
func (*Instance) ShouldRefreshDiff ¶
ShouldRefreshDiff reports whether a metadata tick needs to re-run the diff backend for this instance. It returns true when:
- the instance has no cached diff stats yet (first-time fetch),
- the tmux pane content changed since the last tick (agent wrote files),
- the caller needs full diff content but only short-stats are cached (selection-change upgrade path).
When false, the tick can skip the git subprocess entirely. The paused branch is also short-circuited so the daemon's AutoYes path stays cheap.
func (*Instance) Snapshot ¶
func (i *Instance) Snapshot() InstanceData
Snapshot returns a serialization-safe copy of every Instance field under a single RLock. This is the only safe way to read every field at once from outside the main goroutine. Callers that previously invoked ToInstanceData from background Cmd goroutines (e.g. storage.DeleteInstance) must use this to avoid racing with the main loop's writes (INST-11, STORE-16).
GitWorktree's Get* accessors are pure field reads, so it is safe to call them while holding i.mu — no I/O happens under the lock.
func (*Instance) Start ¶
Start brings the instance online: sets up the worktree, spawns the tmux session, and transitions Ready → Loading → Running. Pass firstTimeSetup=true when the instance is newly created (initial commit, copy user-supplied prompt) and false when loaded from storage. Returns an error if setup fails, leaving the instance in its prior status.
func (*Instance) Started ¶
Started reports whether Start or Resume has completed setup, so the instance has a live tmux session and worktree (or root-repo terminal).
func (*Instance) TapEnter ¶
func (i *Instance) TapEnter()
TapEnter sends a single Enter keystroke to the tmux session when the instance is running and AutoYes is enabled. No-op otherwise. Used by the daemon to auto-dismiss agent prompts without requiring the user to focus the pane.
func (*Instance) TmuxAlive ¶
TmuxAlive returns true if the tmux session is alive. This is a sanity check before attaching.
func (*Instance) TmuxSession ¶
func (i *Instance) TmuxSession() *tmux.TmuxSession
TmuxSession returns the backing tmux session, or nil if the instance has not been started yet. Exposed so the app layer can drive a full-screen attach via tea.ExecProcess.
func (*Instance) ToInstanceData ¶
func (i *Instance) ToInstanceData() InstanceData
ToInstanceData converts an Instance to its serializable form. Kept as a thin wrapper around Snapshot for backwards compatibility with existing callers; new code should prefer Snapshot.
func (*Instance) TransitionTo ¶
TransitionTo validates from→to against the state-machine allow-list and updates Status atomically. Disallowed transitions return an error and leave Status unchanged. Self-transitions are no-ops (success).
func (*Instance) UpdateDiffStats ¶
UpdateDiffStats updates the git diff statistics for this instance
func (*Instance) UpdateDiffStatsShort ¶
UpdateDiffStatsShort updates only the line counts (Added/Removed) without fetching full diff content. Cheaper for non-selected instances that only display counts in the list view.
type InstanceData ¶
type InstanceData struct {
SchemaVersion int `json:"schema_version,omitempty"`
Title string `json:"title"`
Path string `json:"path"`
Branch string `json:"branch"`
Status Status `json:"status"`
Height int `json:"height"`
Width int `json:"width"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
AutoYes bool `json:"auto_yes"`
Program string `json:"program"`
Worktree GitWorktreeData `json:"worktree"`
DiffStats DiffStatsData `json:"diff_stats"`
IsWorkspaceTerminal bool `json:"is_workspace_terminal"`
}
InstanceData represents the serializable data of an Instance.
SchemaVersion is tracked for forward-compatible migrations. A missing field (zero) is interpreted as v0 (pre-versioning); migrations.go upgrades it to CurrentSchemaVersion at decode time.
func Migrate ¶
func Migrate(raw []byte) (InstanceData, error)
Migrate decodes a single raw JSON object representing a stored instance and upgrades it to CurrentSchemaVersion. The function is idempotent: a record already at CurrentSchemaVersion round-trips unchanged.
v0 records (missing SchemaVersion field → decodes to 0) are treated as pre-versioning. The v0→v1 step is a pure field-default upgrade today and exists to establish the migration plumbing; future schema changes extend this switch.
Contributor protocol: when adding/renaming/removing an InstanceData field, bump CurrentSchemaVersion and append a new case to the switch that upgrades from the previous version. The JSON fixture in cmd/workspace_migrate_shape_test.go is a drift guard for the `workspace migrate` CLI's typed mirror struct and must be updated in the same commit.
func MigrateAll ¶
func MigrateAll(rawArray []byte) ([]InstanceData, error)
MigrateAll applies Migrate to every element of a JSON array of raw instance records. Callers that already have []json.RawMessage should prefer this over decoding twice.
type InstanceOptions ¶
type InstanceOptions struct {
// Title is the title of the instance.
Title string
// Path is the path to the workspace.
Path string
// Program is the program to run in the instance (e.g. "claude", "aider --model ollama_chat/gemma3:1b")
Program string
// If AutoYes is true, then
AutoYes bool
// Branch is an existing branch name to start the session on (empty = new branch from HEAD)
Branch string
// ConfigDir is the workspace config directory for worktree resolution.
ConfigDir string
// IsWorkspaceTerminal creates a workspace terminal instance (no worktree).
IsWorkspaceTerminal bool
}
InstanceOptions collects the arguments for NewInstance. All fields except AutoYes, IsWorkspaceTerminal, WsCtx, and ExecutorOverride are required.
type RecoveryAction ¶
type RecoveryAction int
RecoveryAction describes what to do with an instance during startup reconciliation.
const ( // ActionNoChange means the instance is already in a consistent state (e.g. Paused). ActionNoChange RecoveryAction = iota // ActionRestore means tmux + worktree are healthy; do a normal restore. ActionRestore // ActionRestart means tmux is dead but worktree exists; restart with scrollback + agent context. ActionRestart // ActionMarkPaused means both tmux and worktree are gone; mark as Paused (branch is preserved). ActionMarkPaused // ActionKillAndPause means tmux is alive but worktree is gone; kill tmux, mark Paused. ActionKillAndPause // ActionRestartWsTerminal means workspace terminal's tmux is dead; recreate it. ActionRestartWsTerminal )
func DetermineRecoveryAction ¶
func DetermineRecoveryAction(status Status, tmuxAlive, worktreeExists, isWorkspaceTerminal bool) RecoveryAction
DetermineRecoveryAction decides what to do with a loaded instance based on its persisted status and current filesystem/tmux state.
type SessionBackend ¶
type SessionBackend interface {
// RepoName returns the human-visible repo/workspace name used in
// UI labels.
RepoName() (string, error)
// WorkTreePath returns the filesystem directory where the tmux
// session should operate.
WorkTreePath() string
// Diff returns the current diff stats (line counts + content).
Diff() *git.DiffStats
// DiffShort returns diff line counts only, without content body —
// cheaper for non-focused instances that only render counts.
DiffShort() *git.DiffStats
// RefreshBranch returns the current branch name, or empty string
// if the backend doesn't need to refresh (worktrees have a fixed
// branch for their lifetime; workspace terminals track HEAD).
RefreshBranch() string
}
SessionBackend is the polymorphic surface for operations that differ between regular (worktree-backed) instances and workspace terminals. It consolidates scattered IsWorkspaceTerminal branching into a single indirection so new backend types (e.g., remote sessions) can be added by implementing this interface rather than extending a switch.
Scope note: lifecycle operations (Setup/Kill/Pause/Resume) still branch inline in Instance because they interact with shared state (tmux session, lock bookkeeping) in ways that don't fit cleanly behind this interface. Migrating those is a follow-up.
type Status ¶
type Status int
Status is the Instance lifecycle state. Transitions are gated by allowedTransitions in instance.go; use Instance.TransitionTo for every write so invariants hold across the app and tests.
const ( // Running is the status when the instance is running and claude is working. Running Status = iota // Ready is if the claude instance is ready to be interacted with (waiting for user input). Ready // Loading is if the instance is loading (if we are starting it up or something). Loading // Paused is if the instance is paused (worktree removed but branch preserved). Paused // Prompting is when the agent is asking for user permission. Prompting // Deleting is a transient status set immediately when the user confirms // deletion. Cleanup runs asynchronously; on failure the status reverts. Deleting )
type Storage ¶
type Storage struct {
// contains filtered or unexported fields
}
Storage handles saving and loading instances using the state interface
func NewStorage ¶
func NewStorage(state config.InstanceStorage, configDir string) (*Storage, error)
NewStorage creates a new storage instance. configDir is the workspace config directory injected into loaded instances.
func (*Storage) DeleteAllInstances ¶
DeleteAllInstances removes all stored instances
func (*Storage) DeleteInstance ¶
DeleteInstance removes an instance from storage. Operates on raw InstanceData so it does not construct live Instance objects (which would open tmux attach PTYs for every remaining running instance).
func (*Storage) LoadAndReconcile ¶
func (s *Storage) LoadAndReconcile(cmdExec internalexec.Executor) ([]*Instance, error)
LoadAndReconcile loads instance data from disk and reconciles each instance against the live tmux/worktree state. Unlike LoadInstances, a single failing instance is logged and skipped rather than aborting the whole load. This is the correct entry point for any caller that can tolerate reconciliation side effects (killing orphan tmux sessions, marking instances paused).
func (*Storage) LoadInstanceData ¶
func (s *Storage) LoadInstanceData() ([]InstanceData, error)
LoadInstanceData loads raw serialized instance data without constructing Instance objects. Used by reconciliation to inspect state before deciding how to restore. All records pass through Migrate so callers receive CurrentSchemaVersion data.
func (*Storage) LoadInstances ¶
LoadInstances loads the list of instances from disk
func (*Storage) SaveInstances ¶
SaveInstances saves the list of instances to disk. Callers are responsible for filtering out instances that should not be persisted (e.g. Ready-but-not-yet-configured, Deleting) via persistableInstances at the call site. Filtering here on Instance.Started() is unsafe because Kill() flips started=false early (before tmux/worktree teardown), so a save during the kill window would silently drop the instance from disk and cause DeleteInstance to fail with ErrInstanceNotFound.
func (*Storage) UpdateInstance ¶
UpdateInstance replaces the persisted record for an existing instance. Uses the in-memory snapshot of the provided instance and the raw-data load path so the other stored entries are never reconstructed.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package agent consolidates program-specific knowledge for the supported coding agents (claude, aider, gemini, etc.).
|
Package agent consolidates program-specific knowledge for the supported coding agents (claude, aider, gemini, etc.). |
|
Package files provides filesystem enumeration helpers for the file explorer overlay.
|
Package files provides filesystem enumeration helpers for the file explorer overlay. |
|
Package git encapsulates the per-session git worktree: creation, diff stats, push, and cleanup.
|
Package git encapsulates the per-session git worktree: creation, diff stats, push, and cleanup. |
|
Package tmux manages the tmux sessions that drive each agent.
|
Package tmux manages the tmux sessions that drive each agent. |